Search is not available for this dataset
id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
10062250
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Expose canexecute for commands as properties <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Expose canexecute for commands as properties
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062251
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062252
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062253
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062254
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062255
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062256
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062257
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062258
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062259
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062260
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062261
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062262
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062263
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062264
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062265
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); TextEditorModel textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } <MSG> Merge branch 'master' into feature/TextFormatterPort <DFF> @@ -15,7 +15,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -29,7 +29,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -45,7 +45,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -63,7 +63,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -79,7 +79,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -98,7 +98,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -117,7 +117,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; @@ -136,7 +136,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -153,7 +153,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -172,7 +172,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -191,7 +191,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -212,7 +212,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -228,7 +228,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -244,7 +244,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -261,7 +261,7 @@ namespace AvaloniaEdit.Tests.TextMate TextView textView = new TextView(); TextDocument document = new TextDocument(); - TextEditorModel textEditorModel = new TextEditorModel( + using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; @@ -275,5 +275,89 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + using var textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 1"); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 1"); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 2"); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 2"); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, + "Wrong InvalidRange.StartLine 3"); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, + "Wrong InvalidRange.EndLine 3"); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange, + "InvalidRange should not be null"); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange, + "InvalidRange should be null"); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + } } }
99
Merge branch 'master' into feature/TextFormatterPort
15
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10062266
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); module("deleting"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Fix editRowRenderer The method was broken with recent template rendering refactoring. Fixes #444 <DFF> @@ -1387,6 +1387,35 @@ $(function() { deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); + test("editRowRenderer", function() { + var $element = $("#jsGrid"), + + data = [ + { value: "test" } + ], + + gridOptions = { + data: data, + editing: true, + + editRowRenderer: function(item, itemIndex) { + return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); + }, + + fields: [ + { name: "value" } + ] + }, + + grid = new Grid($element, gridOptions); + + grid.editItem(data[0]); + + var $editRow = grid._content.find(".custom-edit-row"); + equal($editRow.length, 1, "edit row rendered"); + equal($editRow.text(), "0:test", "custom edit row renderer rendered"); + }); + module("deleting");
29
Core: Fix editRowRenderer
0
.js
tests
mit
tabalinas/jsgrid
10062267
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); module("deleting"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Fix editRowRenderer The method was broken with recent template rendering refactoring. Fixes #444 <DFF> @@ -1387,6 +1387,35 @@ $(function() { deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); + test("editRowRenderer", function() { + var $element = $("#jsGrid"), + + data = [ + { value: "test" } + ], + + gridOptions = { + data: data, + editing: true, + + editRowRenderer: function(item, itemIndex) { + return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); + }, + + fields: [ + { name: "value" } + ] + }, + + grid = new Grid($element, gridOptions); + + grid.editItem(data[0]); + + var $editRow = grid._content.find(".custom-edit-row"); + equal($editRow.length, 1, "edit row rendered"); + equal($editRow.text(), "0:test", "custom edit row renderer rendered"); + }); + module("deleting");
29
Core: Fix editRowRenderer
0
.js
tests
mit
tabalinas/jsgrid
10062268
<NME> module-helpers.md <BEF> ## Helpers Helpers are small reusable plug-ins that you can write to add extra features to a View module ([working example](http://ftlabs.github.io/fruitmachine/examples/helpers)). ### Defining helpers A helper is simply a function accepting the View module instance as the first argument. The helper can listen to events on the View module and bolt functionality onto the view. Helpers should clear up after themselves. For example if they create variables or bind to events on `setup`, they should be unset and unbound on `teardown`. ```js var myHelper = function(module) { // Add functionality module.on('before setup', function() { /* 1 */ module.sayName = function() { return 'My name is ' + module.name; }; }); // Tidy up module.on('teardown', function() { delete module.sayName; }); }; ``` 1. *It is often useful to hook into the `before setup` event so that added functionality is available inside the module's `setup` function.* ### Attaching helpers At definition: ```js var Apple = fruitmachine.define({ name: 'apple', helpers: [ myHelper ] }); ``` ...or instantiation: ```js var apple = new Apple({ helpers: [ myHelper ] }); ``` ### Using features ```js apple.sayName(); //=> 'My name is apple' ``` ### Community Helpers ("Plugins") Helpers can be released as plugins, if you would like to submit your helper to this list [please raise an issue](https://github.com/ftlabs/fruitmachine/issues). - [fruitmachine-ftdomdelegate](https://github.com/ftlabs/fruitmachine-ftdomdelegate) provides [ftdomdelegate](https://github.com/ftlabs/ftdomdelegate) functionality within fruitmachine modules. <MSG> Merge pull request #75 from ftlabs/helpers Helpers <DFF> @@ -58,3 +58,5 @@ apple.sayName(); Helpers can be released as plugins, if you would like to submit your helper to this list [please raise an issue](https://github.com/ftlabs/fruitmachine/issues). - [fruitmachine-ftdomdelegate](https://github.com/ftlabs/fruitmachine-ftdomdelegate) provides [ftdomdelegate](https://github.com/ftlabs/ftdomdelegate) functionality within fruitmachine modules. +- [fruitmachine-bindall](https://github.com/ftlabs/fruitmachine-bindall) automatically binds all the methods in a module to instances of that module. +- [fruitmachine-media](https://github.com/ftlabs/fruitmachine-media) allows you to create responsive components. Set up media queries for different states and this plugin will allow you to hook into per state setup and teardown events when those media queries match.
2
Merge pull request #75 from ftlabs/helpers
0
.md
md
mit
ftlabs/fruitmachine
10062269
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062270
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062271
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062272
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062273
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062274
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062275
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062276
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062277
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062278
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062279
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062280
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062281
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062282
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062283
<NME> MockStreamGeometryImpl.cs <BEF> using System; using System.Collections.Generic; using Avalonia; using Avalonia.Media; using Avalonia.Platform; namespace AvaloniaEdit.AvaloniaMocks { public class MockStreamGeometryImpl : IStreamGeometryImpl, ITransformedGeometryImpl { private MockStreamGeometryContext _context; public MockStreamGeometryImpl() { Transform = Matrix.Identity; _context = new MockStreamGeometryContext(); } public MockStreamGeometryImpl(Matrix transform) { Transform = transform; _context = new MockStreamGeometryContext(); } private MockStreamGeometryImpl(Matrix transform, MockStreamGeometryContext context) { Transform = transform; _context = context; } public IGeometryImpl SourceGeometry { get; } public Rect Bounds => _context.CalculateBounds(); public Matrix Transform { get; } public double ContourLength => throw new NotImplementedException(); public IStreamGeometryImpl Clone() { return this; } public void Dispose() { } public bool FillContains(Point point) { return _context.FillContains(point); } public bool StrokeContains(IPen pen, Point point) { return false; } public Rect GetRenderBounds(IPen pen) => Bounds; public IGeometryImpl Intersect(IGeometryImpl geometry) { return new MockStreamGeometryImpl(Transform); } public IStreamGeometryContextImpl Open() { return _context; } public ITransformedGeometryImpl WithTransform(Matrix transform) { return new MockStreamGeometryImpl(transform, _context); } public bool TryGetPointAtDistance(double distance, out Point point) { throw new NotImplementedException(); } public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent) { throw new NotImplementedException(); } public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry) { throw new NotImplementedException(); } class MockStreamGeometryContext : IStreamGeometryContextImpl { private List<Point> points = new List<Point>(); public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection) { } public void BeginFigure(Point startPoint, bool isFilled) { points.Add(startPoint); } public Rect CalculateBounds() { var left = double.MaxValue; var right = double.MinValue; var top = double.MaxValue; var bottom = double.MinValue; foreach (var p in points) { left = Math.Min(p.X, left); right = Math.Max(p.X, right); top = Math.Min(p.Y, top); bottom = Math.Max(p.Y, bottom); } return new Rect(new Point(left, top), new Point(right, bottom)); } public void CubicBezierTo(Point point1, Point point2, Point point3) { } public void Dispose() { } public void EndFigure(bool isClosed) { } public void LineTo(Point point) { points.Add(point); } public void QuadraticBezierTo(Point control, Point endPoint) { throw new NotImplementedException(); } public void SetFillRule(FillRule fillRule) { } public bool FillContains(Point point) { // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) { var a = points[i]; var b = points[(i + 1) % points.Count]; var c = points[(i + 2) % points.Count]; Vector v0 = c - a; Vector v1 = b - a; Vector v2 = point - a; var dot00 = v0 * v0; var dot01 = v0 * v1; var dot02 = v0 * v2; var dot11 = v1 * v1; var dot12 = v1 * v2; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; if ((u >= 0) && (v >= 0) && (u + v < 1)) return true; } return false; } } } } <MSG> Merge branch 'master' into feature/ime <DFF> @@ -145,7 +145,7 @@ namespace AvaloniaEdit.AvaloniaMocks public bool FillContains(Point point) { - // Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html + // Use the algorithm from https://www.blackpawn.com/texts/pointinpoly/default.html // to determine if the point is in the geometry (since it will always be convex in this situation) for (int i = 0; i < points.Count; i++) {
1
Merge branch 'master' into feature/ime
1
.cs
Tests/AvaloniaMocks/MockStreamGeometryImpl
mit
AvaloniaUI/AvaloniaEdit
10062284
<NME> module.toJSON.js <BEF> buster.testCase('View#toJSON()', { var apple = new Apple(); var json = apple.toJSON(); expect(json.fmid).toBeTruthy(); }); test("Should fire `tojson` event", function() { var apple = new Apple(); var spy = jest.fn(); apple.on('tojson', spy); apple.toJSON(); expect(spy).toHaveBeenCalled(); }); test("Should be able to manipulate json output via `tojson` event", function() { var apple = new Apple(); apple.on('tojson', function(json) { json.test = 'data'; }); var json = apple.toJSON(); expect(json.test).toEqual('data'); }); test("Should be able to inflate the output", function() { var sandbox = helpers.createSandbox(); var layout = new Layout({ children: { 1: { module: 'apple' } } }); layout .render() .inject(sandbox) .setup(); var layoutEl = layout.el; var appleEl = layout.module('apple').el; var json = layout.toJSON(); var inflated = fruitmachine(json); inflated.setup(); var layoutElInflated = inflated.el; var appleElInflated = inflated.module('apple').el; expect(layoutEl).toEqual(layoutElInflated); assert.equals(layoutEl, layoutElInflated); assert.equals(appleEl, appleElInflated); } }); <MSG> Fix one failing test (assertEquals now checking type); adding in assert/refute where required (buster upgrade problem); fixing a couple of jshint mixed tabs and spaces errors; fixing jshint unused variable error <DFF> @@ -1,3 +1,4 @@ +var assert = buster.assertions.assert; buster.testCase('View#toJSON()', { @@ -56,4 +57,4 @@ buster.testCase('View#toJSON()', { assert.equals(layoutEl, layoutElInflated); assert.equals(appleEl, appleElInflated); } -}); \ No newline at end of file +});
2
Fix one failing test (assertEquals now checking type); adding in assert/refute where required (buster upgrade problem); fixing a couple of jshint mixed tabs and spaces errors; fixing jshint unused variable error
1
.js
toJSON
mit
ftlabs/fruitmachine
10062285
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062286
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062287
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062288
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062289
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062290
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062291
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062292
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062293
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062294
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062295
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062296
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062297
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062298
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062299
<NME> SelectionMouseHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Input; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using System; using System.ComponentModel; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Handles selection of text using the mouse. /// </summary> internal sealed class SelectionMouseHandler : ITextAreaInputHandler { #region enum SelectionMode private enum SelectionMode { /// <summary> /// no selection (no mouse button down) /// </summary> None, /// <summary> /// left mouse button down on selection, might be normal click /// or might be drag'n'drop /// </summary> PossibleDragStart, /// <summary> /// dragging text /// </summary> Drag, /// <summary> /// normal selection (click+drag) /// </summary> Normal, /// <summary> /// whole-word selection (double click+drag or ctrl+click+drag) /// </summary> WholeWord, /// <summary> /// whole-line selection (triple click+drag) /// </summary> WholeLine, /// <summary> /// rectangular selection (alt+click+drag) /// </summary> Rectangular } #endregion private SelectionMode _mode; private AnchorSegment _startWord; private Point _possibleDragStartMousePos; #region Constructor + Attach + Detach public SelectionMouseHandler(TextArea textArea) { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); } public TextArea TextArea { get; } public void Attach() { TextArea.PointerPressed += TextArea_MouseLeftButtonDown; TextArea.PointerMoved += TextArea_MouseMove; TextArea.PointerReleased += TextArea_MouseLeftButtonUp; //textArea.QueryCursor += textArea_QueryCursor; TextArea.OptionChanged += TextArea_OptionChanged; _enableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (_enableTextDragDrop) { AttachDragDrop(); } } public void Detach() { _mode = SelectionMode.None; TextArea.PointerPressed -= TextArea_MouseLeftButtonDown; TextArea.PointerMoved -= TextArea_MouseMove; TextArea.PointerReleased -= TextArea_MouseLeftButtonUp; //textArea.QueryCursor -= textArea_QueryCursor; TextArea.OptionChanged -= TextArea_OptionChanged; if (_enableTextDragDrop) { DetachDragDrop(); } } private void AttachDragDrop() { //textArea.AllowDrop = true; //textArea.GiveFeedback += textArea_GiveFeedback; //textArea.QueryContinueDrag += textArea_QueryContinueDrag; //textArea.DragEnter += textArea_DragEnter; //textArea.DragOver += textArea_DragOver; //textArea.DragLeave += textArea_DragLeave; //textArea.Drop += textArea_Drop; } private void DetachDragDrop() { //textArea.AllowDrop = false; //textArea.GiveFeedback -= textArea_GiveFeedback; //textArea.QueryContinueDrag -= textArea_QueryContinueDrag; //textArea.DragEnter -= textArea_DragEnter; //textArea.DragOver -= textArea_DragOver; //textArea.DragLeave -= textArea_DragLeave; //textArea.Drop -= textArea_Drop; } private bool _enableTextDragDrop; private void TextArea_OptionChanged(object sender, PropertyChangedEventArgs e) { var newEnableTextDragDrop = TextArea.Options.EnableTextDragDrop; if (newEnableTextDragDrop != _enableTextDragDrop) { _enableTextDragDrop = newEnableTextDragDrop; if (newEnableTextDragDrop) AttachDragDrop(); else DetachDragDrop(); } } #endregion #region Dropping text //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragEnter(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // textArea.Caret.Show(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragOver(object sender, DragEventArgs e) //{ // try { // e.Effects = GetEffect(e); // } catch (Exception ex) { // OnDragException(ex); // } //} //DragDropEffects GetEffect(DragEventArgs e) //{ // if (e.Data.GetDataPresent(DataFormats.UnicodeText, true)) { // e.Handled = true; // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e.GetPosition(textArea.TextView), out visualColumn, out isAtEndOfLine); // if (offset >= 0) { // textArea.Caret.Position = new TextViewPosition(textArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; // textArea.Caret.DesiredXPos = double.NaN; // if (textArea.ReadOnlySectionProvider.CanInsert(offset)) { // if ((e.AllowedEffects & DragDropEffects.Move) == DragDropEffects.Move // && (e.KeyStates & DragDropKeyStates.ControlKey) != DragDropKeyStates.ControlKey) // { // return DragDropEffects.Move; // } else { // return e.AllowedEffects & DragDropEffects.Copy; // } // } // } // } // return DragDropEffects.None; //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_DragLeave(object sender, DragEventArgs e) //{ // try { // e.Handled = true; // if (!textArea.IsKeyboardFocusWithin) // textArea.Caret.Hide(); // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_Drop(object sender, DragEventArgs e) //{ // try { // DragDropEffects effect = GetEffect(e); // e.Effects = effect; // if (effect != DragDropEffects.None) { // int start = textArea.Caret.Offset; // if (mode == SelectionMode.Drag && textArea.Selection.Contains(start)) { // Debug.WriteLine("Drop: did not drop: drop target is inside selection"); // e.Effects = DragDropEffects.None; // } else { // Debug.WriteLine("Drop: insert at " + start); // var pastingEventArgs = new DataObjectPastingEventArgs(e.Data, true, DataFormats.UnicodeText); // textArea.RaiseEvent(pastingEventArgs); // if (pastingEventArgs.CommandCancelled) // return; // string text = EditingCommandHandler.GetTextToPaste(pastingEventArgs, textArea); // if (text == null) // return; // bool rectangular = pastingEventArgs.DataObject.GetDataPresent(RectangleSelection.RectangularSelectionDataType); // // Mark the undo group with the currentDragDescriptor, if the drag // // is originating from the same control. This allows combining // // the undo groups when text is moved. // textArea.Document.UndoStack.StartUndoGroup(this.currentDragDescriptor); // try { // if (rectangular && RectangleSelection.PerformRectangularPaste(textArea, textArea.Caret.Position, text, true)) { // } else { // textArea.Document.Insert(start, text); // textArea.Selection = Selection.Create(textArea, start, start + text.Length); // } // } finally { // textArea.Document.UndoStack.EndUndoGroup(); // } // } // e.Handled = true; // } // } catch (Exception ex) { // OnDragException(ex); // } //} //void OnDragException(Exception ex) //{ // // swallows exceptions during drag'n'drop or reports them incorrectly, so // // we re-throw them later to allow the application's unhandled exception handler // // to catch them // textArea.Dispatcher.BeginInvoke( // DispatcherPriority.Send, // new Action(delegate { // throw new DragDropException("Exception during drag'n'drop", ex); // })); //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_GiveFeedback(object sender, GiveFeedbackEventArgs e) //{ // try { // e.UseDefaultCursors = true; // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} //[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] //void textArea_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) //{ // try { // if (e.EscapePressed) { // e.Action = DragAction.Cancel; // } else if ((e.KeyStates & DragDropKeyStates.LeftMouseButton) != DragDropKeyStates.LeftMouseButton) { // e.Action = DragAction.Drop; // } else { // e.Action = DragAction.Continue; // } // e.Handled = true; // } catch (Exception ex) { // OnDragException(ex); // } //} #endregion #region Start Drag //object currentDragDescriptor; //void StartDrag() //{ // // prevent nested StartDrag calls // mode = SelectionMode.Drag; // // mouse capture and Drag'n'Drop doesn't mix // textArea.ReleaseMouseCapture(); // DataObject dataObject = textArea.Selection.CreateDataObject(textArea); // DragDropEffects allowedEffects = DragDropEffects.All; // var deleteOnMove = textArea.Selection.Segments.Select(s => new AnchorSegment(textArea.Document, s)).ToList(); // foreach (ISegment s in deleteOnMove) { // ISegment[] result = textArea.GetDeletableSegments(s); // if (result.Length != 1 || result[0].Offset != s.Offset || result[0].EndOffset != s.EndOffset) { // allowedEffects &= ~DragDropEffects.Move; // } // } // var copyingEventArgs = new DataObjectCopyingEventArgs(dataObject, true); // textArea.RaiseEvent(copyingEventArgs); // if (copyingEventArgs.CommandCancelled) // return; // object dragDescriptor = new object(); // this.currentDragDescriptor = dragDescriptor; // DragDropEffects resultEffect; // using (textArea.AllowCaretOutsideSelection()) { // var oldCaretPosition = textArea.Caret.Position; // try { // Debug.WriteLine("DoDragDrop with allowedEffects=" + allowedEffects); // resultEffect = DragDrop.DoDragDrop(textArea, dataObject, allowedEffects); // Debug.WriteLine("DoDragDrop done, resultEffect=" + resultEffect); // } catch (COMException ex) { // // ignore COM errors - don't crash on badly implemented drop targets // Debug.WriteLine("DoDragDrop failed: " + ex.ToString()); // return; // } // if (resultEffect == DragDropEffects.None) { // // reset caret if drag was aborted // textArea.Caret.Position = oldCaretPosition; // } // } // this.currentDragDescriptor = null; // if (deleteOnMove != null && resultEffect == DragDropEffects.Move && (allowedEffects & DragDropEffects.Move) == DragDropEffects.Move) { // bool draggedInsideSingleDocument = (dragDescriptor == textArea.Document.UndoStack.LastGroupDescriptor); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.StartContinuedUndoGroup(null); // textArea.Document.BeginUpdate(); // try { // foreach (ISegment s in deleteOnMove) { // textArea.Document.Remove(s.Offset, s.Length); // } // } finally { // textArea.Document.EndUpdate(); // if (draggedInsideSingleDocument) // textArea.Document.UndoStack.EndUndoGroup(); // } // } //} #endregion #region QueryCursor // provide the IBeam Cursor for the text area //void textArea_QueryCursor(object sender, QueryCursorEventArgs e) //{ // if (!e.Handled) { // if (mode != SelectionMode.None) { // // during selection, use IBeam cursor even outside the text area // e.Cursor = Cursors.IBeam; // e.Handled = true; // } else if (textArea.TextView.VisualLinesValid) { // // Only query the cursor if the visual lines are valid. // // If they are invalid, the cursor will get re-queried when the visual lines // // get refreshed. // Point p = e.GetPosition(textArea.TextView); // if (p.X >= 0 && p.Y >= 0 && p.X <= textArea.TextView.ActualWidth && p.Y <= textArea.TextView.ActualHeight) { // int visualColumn; // bool isAtEndOfLine; // int offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); // if (enableTextDragDrop && textArea.Selection.Contains(offset)) // e.Cursor = Cursors.Arrow; // else // e.Cursor = Cursors.IBeam; // e.Handled = true; // } // } // } //} #endregion #region LeftButtonDown private void TextArea_MouseLeftButtonDown(object sender, PointerPressedEventArgs e) { if (e.GetCurrentPoint(TextArea).Properties.IsLeftButtonPressed == false) { if (TextArea.RightClickMovesCaret == true && e.Handled == false) { SetCaretOffsetToMousePosition(e); } } else { TextArea.Cursor = Cursor.Parse("IBeam"); var pointer = e.GetCurrentPoint(TextArea); { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); if (_enableTextDragDrop && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset)) { if (TextArea.CapturePointer(e.Pointer)) { _mode = SelectionMode.PossibleDragStart; _possibleDragStartMousePos = e.GetPosition(TextArea); } e.Handled = true; return; } } var oldPosition = TextArea.Caret.Position; SetCaretOffsetToMousePosition(e); if (!shift) { TextArea.ClearSelection(); } if (TextArea.CapturePointer(e.Pointer)) { if (modifiers.HasFlag(KeyModifiers.Alt) && TextArea.Options.EnableRectangularSelection) { _mode = SelectionMode.Rectangular; if (shift && TextArea.Selection is RectangleSelection) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (modifiers.HasFlag(KeyModifiers.Control) && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.WholeWord; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else if (pointer.Properties.IsLeftButtonPressed && e.ClickCount == 1) // e.ClickCount == 1 { _mode = SelectionMode.Normal; if (shift && !(TextArea.Selection is RectangleSelection)) { TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } } else { SimpleSegment startWord; if (e.ClickCount == 3) { _mode = SelectionMode.WholeLine; startWord = GetLineAtMousePosition(e); } else { _mode = SelectionMode.WholeWord; startWord = GetWordAtMousePosition(e); } if (startWord == SimpleSegment.Invalid) { _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); return; } if (shift && !TextArea.Selection.IsEmpty) { if (startWord.Offset < TextArea.Selection.SurroundingSegment.Offset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.Offset))); } else if (startWord.EndOffset > TextArea.Selection.SurroundingSegment.EndOffset) { TextArea.Selection = TextArea.Selection.SetEndpoint(new TextViewPosition(TextArea.Document.GetLocation(startWord.EndOffset))); } _startWord = new AnchorSegment(TextArea.Document, TextArea.Selection.SurroundingSegment); } else { TextArea.Selection = Selection.Create(TextArea, startWord.Offset, startWord.EndOffset); _startWord = new AnchorSegment(TextArea.Document, startWord.Offset, startWord.Length); } } } e.Handled = true; } } } #endregion #region LeftButtonClick #endregion #region LeftButtonDoubleTap #endregion #region Mouse Position <-> Text coordinates private SimpleSegment GetWordAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { var visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace); var wordStartVc = line.GetNextCaretPosition(visualColumn + 1, LogicalDirection.Backward, CaretPositioningMode.WordStartOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordStartVc == -1) wordStartVc = 0; var wordEndVc = line.GetNextCaretPosition(wordStartVc, LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol, TextArea.Selection.EnableVirtualSpace); if (wordEndVc == -1) wordEndVc = line.VisualLength; var relOffset = line.FirstDocumentLine.Offset; var wordStartOffset = line.GetRelativeOffset(wordStartVc) + relOffset; var wordEndOffset = line.GetRelativeOffset(wordEndVc) + relOffset; return new SimpleSegment(wordStartOffset, wordEndOffset - wordStartOffset); } else { return SimpleSegment.Invalid; } } private SimpleSegment GetLineAtMousePosition(PointerEventArgs e) { var textView = TextArea.TextView; if (textView == null) return SimpleSegment.Invalid; var pos = e.GetPosition(textView); if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; var line = textView.GetVisualLineFromVisualTop(pos.Y); return line != null && line.TextLines != null ? new SimpleSegment(line.StartOffset, line.LastDocumentLine.EndOffset - line.StartOffset) : SimpleSegment.Invalid; } private int GetOffsetFromMousePosition(PointerEventArgs e, out int visualColumn, out bool isAtEndOfLine) { return GetOffsetFromMousePosition(e.GetPosition(TextArea.TextView), out visualColumn, out isAtEndOfLine); } private int GetOffsetFromMousePosition(Point positionRelativeToTextView, out int visualColumn, out bool isAtEndOfLine) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(pos, TextArea.Selection.EnableVirtualSpace, out isAtEndOfLine); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } isAtEndOfLine = false; return -1; } private int GetOffsetFromMousePositionFirstTextLineOnly(Point positionRelativeToTextView, out int visualColumn) { visualColumn = 0; var textView = TextArea.TextView; var pos = positionRelativeToTextView; if (pos.Y < 0) pos = pos.WithY(0); if (pos.Y > textView.Bounds.Height) pos = pos.WithY(textView.Bounds.Height); pos += textView.ScrollOffset; if (pos.Y >= textView.DocumentHeight) pos = pos.WithY(textView.DocumentHeight - ExtensionMethods.Epsilon); var line = textView.GetVisualLineFromVisualTop(pos.Y); if (line != null && line.TextLines != null) { visualColumn = line.GetVisualColumn(line.TextLines.First(), pos.X, TextArea.Selection.EnableVirtualSpace); return line.GetRelativeOffset(visualColumn) + line.FirstDocumentLine.Offset; } return -1; } #endregion private const int MinimumHorizontalDragDistance = 2; private const int MinimumVerticalDragDistance = 2; #region MouseMove private void TextArea_MouseMove(object sender, PointerEventArgs e) { if (e.Handled) return; if (_mode == SelectionMode.Normal || _mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine || _mode == SelectionMode.Rectangular) { e.Handled = true; if (TextArea.TextView.VisualLinesValid) { // If the visual lines are not valid, don't extend the selection. // Extending the selection forces a VisualLine refresh, and it is sufficient // to do that on MouseUp, we don't have to do it every MouseMove. ExtendSelectionToMouse(e); } } else if (_mode == SelectionMode.PossibleDragStart) { e.Handled = true; Vector mouseMovement = e.GetPosition(TextArea) - _possibleDragStartMousePos; if (Math.Abs(mouseMovement.X) > MinimumHorizontalDragDistance || Math.Abs(mouseMovement.Y) > MinimumVerticalDragDistance) { // TODO: drag //StartDrag(); } } } #endregion #region ExtendSelection private void SetCaretOffsetToMousePosition(PointerEventArgs e, ISegment allowedSegment = null) { int visualColumn; bool isAtEndOfLine; int offset; if (_mode == SelectionMode.Rectangular) { offset = GetOffsetFromMousePositionFirstTextLineOnly(e.GetPosition(TextArea.TextView), out visualColumn); isAtEndOfLine = true; } else { offset = GetOffsetFromMousePosition(e, out visualColumn, out isAtEndOfLine); } if (allowedSegment != null) { offset = offset.CoerceValue(allowedSegment.Offset, allowedSegment.EndOffset); } if (offset >= 0) { TextArea.Caret.Position = new TextViewPosition(TextArea.Document.GetLocation(offset), visualColumn) { IsAtEndOfLine = isAtEndOfLine }; TextArea.Caret.DesiredXPos = double.NaN; } } private void ExtendSelectionToMouse(PointerEventArgs e) { var oldPosition = TextArea.Caret.Position; if (_mode == SelectionMode.Normal || _mode == SelectionMode.Rectangular) { SetCaretOffsetToMousePosition(e); if (_mode == SelectionMode.Normal && TextArea.Selection is RectangleSelection) TextArea.Selection = new SimpleSelection(TextArea, oldPosition, TextArea.Caret.Position); else if (_mode == SelectionMode.Rectangular && !(TextArea.Selection is RectangleSelection)) TextArea.Selection = new RectangleSelection(TextArea, oldPosition, TextArea.Caret.Position); else TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position); } else if (_mode == SelectionMode.WholeWord || _mode == SelectionMode.WholeLine) { var newWord = (_mode == SelectionMode.WholeLine) ? GetLineAtMousePosition(e) : GetWordAtMousePosition(e); if (newWord != SimpleSegment.Invalid && _startWord != null) { TextArea.Selection = Selection.Create(TextArea, Math.Min(newWord.Offset, _startWord.Offset), Math.Max(newWord.EndOffset, _startWord.EndOffset)); // moves caret to start or end of selection TextArea.Caret.Offset = newWord.Offset < _startWord.Offset ? newWord.Offset : Math.Max(newWord.EndOffset, _startWord.EndOffset); } } TextArea.Caret.BringCaretToView(0); } #endregion #region MouseLeftButtonUp private void TextArea_MouseLeftButtonUp(object sender, PointerEventArgs e) { if (_mode == SelectionMode.None || e.Handled) return; e.Handled = true; switch (_mode) { case SelectionMode.PossibleDragStart: // this was not a drag start (mouse didn't move after mousedown) SetCaretOffsetToMousePosition(e); TextArea.ClearSelection(); break; case SelectionMode.Normal: case SelectionMode.WholeWord: case SelectionMode.WholeLine: case SelectionMode.Rectangular: if (TextArea.Options.ExtendSelectionOnMouseUp) ExtendSelectionToMouse(e); break; } _mode = SelectionMode.None; TextArea.ReleasePointerCapture(e.Pointer); } #endregion } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -410,7 +410,7 @@ namespace AvaloniaEdit.Editing { var modifiers = e.KeyModifiers; var shift = modifiers.HasFlag(KeyModifiers.Shift); - if (_enableTextDragDrop && !shift) + if (_enableTextDragDrop && e.ClickCount == 1 && !shift) { var offset = GetOffsetFromMousePosition(e, out _, out _); if (TextArea.Selection.Contains(offset))
1
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062300
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); } fm.create = module.exports; fm.Model = options.Model; fm.Events = events; fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; }, wrapHTML: function(html) { return '<' + this.tag + ' class="' + this.module + ' ' + this.classes.join(' ') + '" id="' + this.fmid() + '">' + html + '</div>'; }, purgeHtmlCache: function() { } else { window['FruitMachine'] = FruitMachine; } }()); <MSG> - closes custom tag in wrapHTML() <DFF> @@ -426,7 +426,7 @@ }, wrapHTML: function(html) { - return '<' + this.tag + ' class="' + this.module + ' ' + this.classes.join(' ') + '" id="' + this.fmid() + '">' + html + '</div>'; + return '<' + this.tag + ' class="' + this.module + ' ' + this.classes.join(' ') + '" id="' + this.fmid() + '">' + html + '</' + this.tag + '>'; }, purgeHtmlCache: function() { @@ -842,4 +842,4 @@ } else { window['FruitMachine'] = FruitMachine; } -}()); \ No newline at end of file +}());
2
- closes custom tag in wrapHTML()
2
.js
js
mit
ftlabs/fruitmachine
10062301
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062302
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062303
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062304
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062305
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062306
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062307
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062308
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062309
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062310
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062311
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062312
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062313
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062314
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062315
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> <Version>0.10.12.2</Version> </PropertyGroup> </Project> <MSG> Replace tab by spaces <DFF> @@ -5,6 +5,6 @@ <AvaloniaVersion>0.10.12</AvaloniaVersion> <TextMateSharpVersion>1.0.34</TextMateSharpVersion> <NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion> - <Version>0.10.12.2</Version> + <Version>0.10.12.2</Version> </PropertyGroup> </Project>
1
Replace tab by spaces
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10062316
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062317
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062318
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062319
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062320
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062321
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062322
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062323
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062324
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062325
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062326
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062327
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062328
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062329
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062330
<NME> TextFormatterFactory.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> internal static class TextFormatterFactory { public static TextFormatter Create() { /// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object. /// </summary> public static TextFormatter Create(Control owner) { return TextFormatter.Current; } /// <summary> /// Creates formatted text. /// </summary> /// <param name="element">The owner element. The text formatter setting are read from this element.</param> /// <param name="text">The text.</param> /// <param name="typeface">The typeface to use. If this parameter is null, the typeface of the <paramref name="element"/> will be used.</param> /// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param> /// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param> /// <returns>A FormattedText object using the specified settings.</returns> public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground) { if (element == null) throw new ArgumentNullException(nameof(element)); if (text == null) throw new ArgumentNullException(nameof(text)); if (typeface == default) typeface = element.CreateTypeface(); if (emSize == null) emSize = TextElement.GetFontSize(element); if (foreground == null) foreground = TextElement.GetForeground(element); return new FormattedText( text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, emSize.Value, foreground); } } } <MSG> text formatter factory is public. Reason is that LineNumberMargin should be written in code that an external user could have written. <DFF> @@ -27,7 +27,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0. /// </summary> - internal static class TextFormatterFactory + public static class TextFormatterFactory { public static TextFormatter Create() {
1
text formatter factory is public.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062331
<NME> README.md <BEF> # jsGrid Lightweight Grid jQuery Plugin [![Build Status](https://travis-ci.org/tabalinas/jsgrid.svg?branch=master)](https://travis-ci.org/tabalinas/jsgrid) Project site [js-grid.com](http://js-grid.com/) **jsGrid** is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging, sorting, and validating. jsGrid is tunable and allows to customize appearance and components. ![jsGrid lightweight client-side data grid](http://content.screencast.com/users/tabalinas/folders/Jing/media/beada891-57fc-41f3-ad77-fbacecd01d15/00000002.png) ## Table of contents * [Demos](#demos) * [Installation](#installation) * [Basic Usage](#basic-usage) * [Configuration](#configuration) * [Grid Fields](#grid-fields) * [Methods](#methods) * [Callbacks](#callbacks) * [Grid Controller](#grid-controller) * [Validation](#validation) * [Localization](#localization) * [Sorting Strategies](#sorting-strategies) * [Load Strategies](#load-strategies) * [Load Indication](#load-indication) * [Requirement](#requirement) * [Compatibility](#compatibility) ## Demos See [Demos](http://js-grid.com/demos/) on project site. Sample projects showing how to use jsGrid with the most popular backend technologies * **PHP** - https://github.com/tabalinas/jsgrid-php * **ASP.NET WebAPI** - https://github.com/tabalinas/jsgrid-webapi * **Express (NodeJS)** - https://github.com/tabalinas/jsgrid-express * **Ruby on Rail** - https://github.com/tabalinas/jsgrid-rails * **Django (Python)** - https://github.com/tabalinas/jsgrid-django ## Installation Install jsgrid with bower: ```bash $ bower install js-grid --save ``` Find jsGrid cdn links [here](https://cdnjs.com/libraries/jsgrid). ## Basic Usage Ensure that jQuery library of version 1.8.3 or later is included. Include `jsgrid.min.js`, `jsgrid-theme.min.css`, and `jsgrid.min.css` files into the web page. Create grid applying jQuery plugin `jsGrid` with grid config as follows: ```javascript $("#jsGrid").jsGrid({ width: "100%", height: "400px", filtering: true, editing: true, sorting: true, paging: true, data: db.clients, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] }); ``` ## Configuration The config object may contain following options (default values are specified below): ```javascript { fields: [], data: [], autoload: false, controller: { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, width: "auto", height: "auto", heading: true, filtering: false, inserting: false, editing: false, selecting: true, sorting: false, paging: false, pageLoading: false, insertRowLocation: "bottom", rowClass: function(item, itemIndex) { ... }, rowClick: function(args) { ... }, rowDoubleClick: function(args) { ... }, noDataContent: "Not found", confirmDeleting: true, deleteConfirm: "Are you sure?", pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", invalidNotify: function(args) { ... } invalidMessage: "Invalid data entered!", loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, loadIndicator: function(config) { ... } loadStrategy: function(config) { ... } updateOnResize: true, rowRenderer: null, headerRowRenderer: null, filterRowRenderer: null, insertRowRenderer: null, editRowRenderer: null, pagerRenderer: null } ``` ### fields An array of fields (columns) of the grid. Each field has general options and specific options depending on field type. General options peculiar to all field types: ```javascript { type: "", name: "", title: "", align: "", width: 100, visible: true, css: "", headercss: "", filtercss: "", insertcss: "", editcss: "", filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", headerTemplate: function() { ... }, itemTemplate: function(value, item) { ... }, filterTemplate: function() { ... }, insertTemplate: function() { ... }, editTemplate: function(value, item) { ... }, filterValue: function() { ... }, insertValue: function() { ... }, editValue: function() { ... }, cellRenderer: null, validate: null } ``` - **type** is a string key of field (`"text"|"number"|"checkbox"|"select"|"textarea"|"control"`) in fields registry `jsGrid.fields` (the registry can be easily extended with custom field types). - **name** is a property of data item associated with the column. - **title** is a text to be displayed in the header of the column. If `title` is not specified, the `name` will be used instead. - **align** is alignment of text in the cell. Accepts following values `"left"|"center"|"right"`. - **width** is a width of the column. - **visible** is a boolean specifying whether to show a column or not. (version added: 1.3) - **css** is a string representing css classes to be attached to the table cell. - **headercss** is a string representing css classes to be attached to the table header cell. If not specified, then **css** is attached instead. - **filtercss** is a string representing css classes to be attached to the table filter row cell. If not specified, then **css** is attached instead. - **insertcss** is a string representing css classes to be attached to the table insert row cell. If not specified, then **css** is attached instead. - **editcss** is a string representing css classes to be attached to the table edit row cell. If not specified, then **css** is attached instead. - **filtering** is a boolean specifying whether or not column has filtering (`filterTemplate()` is rendered and `filterValue()` is included in load filter object). - **inserting** is a boolean specifying whether or not column has inserting (`insertTemplate()` is rendered and `insertValue()` is included in inserting item). - **editing** is a boolean specifying whether or not column has editing (`editTemplate()` is rendered and `editValue()` is included in editing item). - **sorting** is a boolean specifying whether or not column has sorting ability. - **sorter** is a string or a function specifying how to sort item by the field. The string is a key of sorting strategy in the registry `jsGrid.sortStrategies` (the registry can be easily extended with custom sorting functions). Sorting function has the signature `function(value1, value2) { return -1|0|1; }`. - **headerTemplate** is a function to create column header content. It should return markup as string, DomNode or jQueryElement. - **itemTemplate** is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterTemplate** is a function to create filter row cell content. It should return markup as string, DomNode or jQueryElement. - **insertTemplate** is a function to create insert row cell content. It should return markup as string, DomNode or jQueryElement. - **editTemplate** is a function to create cell content of editing row. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterValue** is a function returning the value of filter property associated with the column. - **insertValue** is a function returning the value of inserting item property associated with the column. - **editValue** is a function returning the value of editing item property associated with the column. - **cellRenderer** is a function to customize cell rendering. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. The function should return markup as a string, jQueryElement or DomNode representing table cell `td`. - **validate** is a string as validate rule name or validation function or a validation configuration object or an array of validation configuration objects. Read more details about validation in the [Validation section](#validation). Specific field options depends on concrete field type. Read about build-in fields in [Grid Fields](#grid-fields) section. ### data An array of items to be displayed in the grid. The option should be used to provide static data. Use the `controller` option to provide non static data. ### autoload (default `false`) A boolean value specifying whether `controller.loadData` will be called when grid is rendered. ### controller An object or function returning an object with the following structure: ```javascript { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop } ``` - **loadData** is a function returning an array of data or jQuery promise that will be resolved with an array of data (when `pageLoading` is `true` instead of object the structure `{ data: [items], itemsCount: [total items count] }` should be returned). Accepts filter parameter including current filter options and paging parameters when `pageLoading` is `true`. - **insertItem** is a function returning inserted item or jQuery promise that will be resolved with inserted item. Accepts inserting item object. - **updateItem** is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object. - **deleteItem** is a function deleting item. Returns jQuery promise that will be resolved when deletion is completed. Accepts deleting item object. Read more about controller interface in [Grid Controller](#grid-controller) section. ### width (default: `"auto"`) Specifies the overall width of the grid. Accepts all value types accepting by `jQuery.width`. ### height (default: `"auto"`) Specifies the overall height of the grid including the pager. Accepts all value types accepting by `jQuery.height`. ### heading (default: `true`) A boolean value specifies whether to show grid header or not. ### filtering (default: `false`) A boolean value specifies whether to show filter row or not. ### inserting (default: `false`) A boolean value specifies whether to show inserting row or not. ### editing (default: `false`) A boolean value specifies whether editing is allowed. ### selecting (default: `true`) A boolean value specifies whether to highlight grid rows on hover. ### sorting (default: `false`) A boolean value specifies whether sorting is allowed. ### paging (default: `false`) A boolean value specifies whether data is displayed by pages. ### pageLoading (default: `false`) A boolean value specifies whether to load data by page. When `pageLoading` is `true` the `loadData` method of controller accepts `filter` parameter with two additional properties `pageSize` and `pageIndex`. ### insertRowLocation (default: `"bottom"`) Specifies the location of an inserted row within the grid. When `insertRowLocation` is `"bottom"` the new row will appear at the bottom of the grid. When set to `"top"`, the new row will appear at the top. ### rowClass A string or a function specifying row css classes. A string contains classes separated with spaces. A function has signature `function(item, itemIndex)`. It accepts the data item and index of the item. It should returns a string containing classes separated with spaces. ### rowClick A function handling row click. Accepts single argument with following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` By default `rowClick` performs row editing when `editing` is `true`. ### rowDoubleClick A function handling row double click. Accepts single argument with the following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` ### noDataContent (default `"Not found"`) A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when `data` is an empty array. ### confirmDeleting (default `true`) A boolean value specifying whether to ask user to confirm item deletion. ### deleteConfirm (default `"Are you sure?"`) A string or a function returning string specifying delete confirmation message to be displayed to the user. A function has the signature `function(item)` and accepts item to be deleted. ### pagerContainer (default `null`) A jQueryElement or DomNode to specify where to render a pager. Used for external pager rendering. When it is equal to `null`, the pager is rendered at the bottom of the grid. ### pageIndex (default `1`) An integer value specifying current page index. Applied only when `paging` is `true`. ### pageSize (default `20`) An integer value specifying the amount of items on the page. Applied only when `paging` is `true`. ### pageButtonCount (default `15`) An integer value specifying the maximum amount of page buttons to be displayed in the pager. ### pagerFormat A string specifying pager format. The default value is `"Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}"` There are placeholders that can be used in the format: ```javascript {first} // link to first page {prev} // link to previous page {pages} // page links {next} // link to next page {last} // link to last page {pageIndex} // current page index {pageCount} // total amount of pages {itemCount} // total amount of items ``` ### pageNextText (default `"Next"`) A string specifying the text of the link to the next page. ### pagePrevText (default `"Prev"`) A string specifying the text of the link to the previous page. ### pageFirstText (default `"First"`) A string specifying the text of the link to the first page. ### pageLastText (default `"Last"`) A string specifying the text of the link to the last page. ### pageNavigatorNextText (default `"..."`) A string specifying the text of the link to move to next set of page links, when total amount of pages more than `pageButtonCount`. ### pageNavigatorPrevText (default `"..."`) A string specifying the text of the link to move to previous set of page links, when total amount of pages more than `pageButtonCount`. ### invalidMessage (default `"Invalid data entered!"`) A string specifying the text of the alert message, when invalid data was entered. ### invalidNotify A function triggered, when invalid data was entered. By default all violated validators messages are alerted. The behavior can be customized by providing custom function. The function accepts a single argument with the following structure: ```javascript { item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` In the following example error messages are printed in the console instead of alerting: ```javascript $("#grid").jsGrid({ ... invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.field + ": " + error.message; }); console.log(messages); } ... }); ``` ### loadIndication (default `true`) A boolean value specifying whether to show loading indication during controller operations execution. ### loadIndicationDelay (default `500`) An integer value specifying the delay in ms before showing load indication. Applied only when `loadIndication` is `true`. ### loadMessage (default `"Please, wait..."`) A string specifying the text of loading indication panel. Applied only when `loadIndication` is `true`. ### loadShading (default `true`) A boolean value specifying whether to show overlay (shader) over grid content during loading indication. Applied only when `loadIndication` is `true`. ### loadIndicator An object or a function returning an object representing grid load indicator. Load indicator could be any js object supporting two methods `show` and `hide`. `show` is called on each loading start. `hide` method is called on each loading finish. Read more about custom load indicator in the [Load Indication](#load-indication) section. ### loadStrategy An object or a function returning an object representing grid load strategy. Load strategy defines behavior of the grid after loading data (any interaction with grid controller methods including data manipulation like inserting, updating and removing). There are two build-in load strategies: `DirectLoadingStrategy` and `PageLoadingStrategy`. Load strategy depends on `pageLoading` option value. For advanced scenarios custom load strategy can be provided. Read more about custom load strategies in the [Load Strategies](#load-strategies) section. ### updateOnResize (default `true`) A boolean value specifying whether to refresh grid on window resize event. ### rowRenderer (default `null`) A function to customize row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### headerRowRenderer (default `null`) A function to customize grid header row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### filterRowRenderer (default `null`) A function to customize grid filter row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### insertRowRenderer (default `null`) A function to customize grid inserting row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### editRowRenderer (default `null`) A function to customize editing row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### pagerRenderer (default `null`) > version added: 1.2 A function to customize pager rendering. The function accepts a single argument with the following structure: ```javascript { pageIndex, // index of the currently opened page pageCount // total amount of grid pages } ``` The function should return markup as a string, jQueryElement or DomNode representing the pager. If `pagerRenderer` is specified, then `pagerFormat` option will be ignored. ## Grid Fields All fields supporting by grid are stored in `jsGrid.fields` object, where key is a type of the field and the value is the field class. `jsGrid.fields` contains following build-in fields: ```javascript { text: { ... }, // simple text input number: { ... }, // number input select: { ... }, // select control checkbox: { ... }, // checkbox input textarea: { ... }, // textarea control (renders textarea for inserting and editing and text input for filtering) control: { ... } // control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row } ``` Each build-in field can be easily customized with general configuration properties described in [fields](#fields) section and custom field-specific properties described below. ### text Text field renders `<input type="text">` in filter, inserting and editing rows. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### number Number field renders `<input type="number">` in filter, inserting and editing rows. Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "right", // right text alignment readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### select Select field renders `<select>` control in filter, inserting and editing rows. Custom properties: ```javascript { align: "center", // center text alignment autosearch: true, // triggers searching when the user changes the selected item in the filter items: [], // an array of items for select valueField: "", // name of property of item to be used as value textField: "", // name of property of item to be used as displaying value selectedIndex: -1, // index of selected item by default valueType: "number|string", // the data type of the value readOnly: false // a boolean defines whether select is readonly (added in v1.4) } ``` If valueField is not defined, then the item index is used instead. If textField is not defined, then item itself is used to display value. For instance the simple select field config may look like: ```javascript { name: "Country", type: "select", items: [ "", "United States", "Canada", "United Kingdom" ] } ``` or more complex with items as objects: ```javascript { name: "Country", type: "select" items: [ { Name: "", Id: 0 }, { Name: "United States", Id: 1 }, { Name: "Canada", Id: 2 }, { Name: "United Kingdom", Id: 3 } ], valueField: "Id", textField: "Name" } ``` `valueType` defines whether the field value should be converted to a number or returned as a string. The value of the option is determined automatically depending on the data type of `valueField` of the first item, but it can be overridden. ### checkbox Checkbox field renders `<input type="checkbox">` in filter, inserting and editing rows. Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "center", // center text alignment autosearch: true // triggers searching when the user clicks checkbox in filter } ``` ### textarea Textarea field renders `<textarea>` in inserting and editing rows and `<input type="text">` in filter row. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether textarea is readonly (added in v1.4) } ``` ### control Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. It also renders button switching between filtering and searching in header row. Custom properties: ```javascript { editButton: true, // show edit button deleteButton: true, // show delete button clearFilterButton: true, // show clear filter button modeSwitchButton: true, // show switching filtering/inserting button align: "center", // center content alignment width: 50, // default column width is 50px filtering: false, // disable filtering for column inserting: false, // disable inserting for column editing: false, // disable editing for column sorting: false, // disable sorting for column searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode editButtonTooltip: "Edit", // tooltip of edit item button deleteButtonTooltip: "Delete", // tooltip of delete item button searchButtonTooltip: "Search", // tooltip of search button clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button insertButtonTooltip: "Insert", // tooltip of insert button updateButtonTooltip: "Update", // tooltip of update item button cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button } ``` ### Custom Field If you need a completely custom field, the object `jsGrid.fields` can be easily extended. In this example we define new grid field `date`: ```javascript var MyDateField = function(config) { jsGrid.Field.call(this, config); }; MyDateField.prototype = new jsGrid.Field({ css: "date-field", // redefine general property 'css' align: "center", // redefine general property 'align' myCustomProperty: "foo", // custom property sorter: function(date1, date2) { return new Date(date1) - new Date(date2); }, itemTemplate: function(value) { return new Date(value).toDateString(); }, insertTemplate: function(value) { return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); }, editTemplate: function(value) { return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); }, insertValue: function() { return this._insertPicker.datepicker("getDate").toISOString(); }, editValue: function() { return this._editPicker.datepicker("getDate").toISOString(); } }); jsGrid.fields.date = MyDateField; ``` To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. Here `itemTemplate` just returns the string representation of a date. `insertTemplate` and `editTemplate` create jQuery UI datePicker for inserting and editing row. Of course jquery ui library should be included to make it work. `insertValue` and `editValue` return date to insert and update items accordingly. We also defined date specific sorter. Now, our new field `date` can be used in the grid config as follows: ```javascript { fields: [ ... { type: "date", myCustomProperty: "bar" }, ... ] } ``` ## Methods jsGrid methods could be called with `jsGrid` jQuery plugin or directly. To use jsGrid plugin to call a method, just call `jsGrid` with method name and required parameters as next arguments: ```javascript // calling method with jQuery plugin $("#grid").jsGrid("methodName", param1, param2); ``` To call method directly you need to retrieve grid instance or just create grid with the constructor: ```javascript // retrieve grid instance from element data var grid = $("#grid").data("JSGrid"); // create grid with the constructor var grid = new jsGrid.Grid($("#grid"), { ... }); // call method directly grid.methodName(param1, param2); ``` ### cancelEdit() Cancels row editing. ```javascript $("#grid").jsGrid("cancelEdit"); ``` ### clearFilter(): `Promise` Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed. ```javascript $("#grid").jsGrid("clearFilter").done(function() { console.log("filtering completed"); }); ``` ### clearInsert() Clears current inserting row. ```javascript $("#grid").jsGrid("clearInsert"); ``` ### deleteItem(item|$row|rowNode): `Promise` Removes specified row from the grid. Returns jQuery promise resolved when deletion is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // delete row by item reference $("#grid").jsGrid("deleteItem", item); // delete row by jQueryElement $("#grid").jsGrid("deleteItem", $(".specific-row")); // delete row by DomNode $("#grid").jsGrid("deleteItem", rowNode); ``` ### destroy() Destroys the grid and brings the Node to its original state. ```javascript $("#grid").jsGrid("destroy"); ``` ### editItem(item|$row|rowNode) Sets grid editing row. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // edit row by item reference $("#grid").jsGrid("editItem", item); // edit row by jQueryElement $("#grid").jsGrid("editItem", $(".specific-row")); // edit row by DomNode $("#grid").jsGrid("editItem", rowNode); ``` ### getFilter(): `Object` Get grid filter as a plain object. ```javascript var filter = $("#grid").jsGrid("getFilter"); ``` ### getSorting(): `Object` > version added: 1.2 Get grid current sorting params as a plain object with the following format: ```javascript { field, // the name of the field by which grid is sorted order // 'asc' or 'desc' depending on sort order } ``` ```javascript var sorting = $("#grid").jsGrid("getSorting"); ``` ### fieldOption(fieldName|fieldIndex, optionName, [optionValue]) > version added: 1.3 Gets or sets the value of a field option. **fieldName|fieldIndex** is the name or the index of the field to get/set the option value (if the grid contains more than one field with the same name, the first field will be used). **optionName** is the name of the field option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the field option `optionName` will be returned. ```javascript // hide the field "ClientName" $("#grid").jsGrid("fieldOption", "ClientName", "visible", false); // get width of the 2nd field var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width"); ``` ### insertItem([item]): `Promise` Inserts row into the grid based on item. Returns jQuery promise resolved when insertion is completed. **item** is the item to pass to `controller.insertItem`. If `item` is not specified the data from inserting row will be inserted. ```javascript // insert item from inserting row $("#grid").jsGrid("insertItem"); // insert item $("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() { console.log("insertion completed"); }); ``` ### loadData([filter]): `Promise` Loads data calling corresponding `controller.loadData` method. Returns jQuery promise resolved when data loading is completed. It preserves current sorting and paging unlike the `search` method . **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // load data with current grid filter $("#grid").jsGrid("loadData"); // loadData with custom filter $("#grid").jsGrid("loadData", { Name: "John" }).done(function() { console.log("data loaded"); }); ``` ### exportData([options]) Transforms the grid data into the specified output type. Output can be formatted, filtered or modified by providing options. Currently only supports CSV output. ```javascript //Basic export var csv = $("#grid").jsGrid("exportData"); //Full Options var csv = $("#grid").jsGrid("exportData", { type: "csv", //Only CSV supported subset: "all" | "visible", //Visible will only output the currently displayed page delimiter: "|", //If using csv, the character to seperate fields includeHeaders: true, //Include header row in output encapsulate: true, //Surround each field with qoutation marks; needed for some systems newline: "\r\n", //Newline character to use //Takes each item and returns true if it should be included in output. //Executed only on the records within the given subset above. filter: function(item){return true}, //Transformations are a way to modify the display value of the output. //Provide a key of the field name, and a function that takes the current value. transformations: { "Married": function(value){ if (value === true){ return "Yes" } else{ return "No" } } } }); ``` ### openPage(pageIndex) Opens the page of specified index. **pageIndex** is one-based index of the page to open. The value should be in range from 1 to [total amount of pages]. ### option(optionName, [optionValue]) Gets or sets the value of an option. **optionName** is the name of the option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the option `optionName` will be returned. ```javascript // turn off paging $("#grid").jsGrid("option", "paging", false); // get current page index var pageIndex = $("#grid").jsGrid("option", "pageIndex"); ``` ### refresh() Refreshes the grid. Renders the grid body and pager content, recalculates sizes. ```javascript $("#grid").jsGrid("refresh"); ``` ### render(): `Promise` Performs complete grid rendering. If option `autoload` is `true` calls `controller.loadData`. The state of the grid like current page and sorting is retained. Returns jQuery promise resolved when data loading is completed. If auto-loading is disabled the promise is instantly resolved. ```javascript $("#grid").jsGrid("render").done(function() { console.log("rendering completed and data loaded"); }); ``` ### reset() Resets the state of the grid. Goes to the first data page, resets sorting, and then calls `refresh`. ```javascript $("#grid").jsGrid("reset"); ``` ### rowByItem(item): `jQueryElement` > version added: 1.3 Gets the row jQuery element corresponding to the item. **item** is the item corresponding to the row. ```javascript var $row = $("#grid").jsGrid("rowByItem", item); ``` ### search([filter]): `Promise` Performs filtering of the grid. Returns jQuery promise resolved when data loading is completed. It resets current sorting and paging unlike the `loadData` method. **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // search with current grid filter $("#grid").jsGrid("search"); // search with custom filter $("#grid").jsGrid("search", { Name: "John" }).done(function() { console.log("filtering completed"); }); ``` ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showPrevPages"); ``` ### showNextPages() Shows next set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ```` ### insertItem(item): `Promise|insertedItem` Called on item insertion. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid ## Sorting Strategies Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: function() { ... } // called on loading finish } ``` This simple example prints messages to console instead of showing load indicator: ```javascript { loadIndicator: { show: function() { console.log("loading started"); }, hide: function() { console.log("loading finished"); } } } ``` If `loadIndicator` is a function, it accepts the config of load indicator in the following format: ```javascript { container, // grid container div message, // the loading message is a value of the option loadMessage shading // the boolean value defining whether to show shading. This is a value of the option loadShading } ``` The similar example printing messages to console shows how to configure loading indicator with a function returning an object: ```javascript { loadIndicator: function(config) { return { show: function() { console.log("loading started: " + config.message); }, hide: function() { console.log("loading finished"); } }; } } ``` Customization of loading indicator is useful, when you want to use any external load indicator that is used for all other ajax requests on the page. This example shows how to use [spin.js](http://fgnass.github.io/spin.js/) to indicate loading: ```javascript { loadIndicator: function(config) { var container = config.container[0]; var spinner = new Spinner(); return { show: function() { spinner.spin(container); }, hide:
74
Docs: Sorting strategies descirption
1
.md
md
mit
tabalinas/jsgrid
10062332
<NME> README.md <BEF> # jsGrid Lightweight Grid jQuery Plugin [![Build Status](https://travis-ci.org/tabalinas/jsgrid.svg?branch=master)](https://travis-ci.org/tabalinas/jsgrid) Project site [js-grid.com](http://js-grid.com/) **jsGrid** is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging, sorting, and validating. jsGrid is tunable and allows to customize appearance and components. ![jsGrid lightweight client-side data grid](http://content.screencast.com/users/tabalinas/folders/Jing/media/beada891-57fc-41f3-ad77-fbacecd01d15/00000002.png) ## Table of contents * [Demos](#demos) * [Installation](#installation) * [Basic Usage](#basic-usage) * [Configuration](#configuration) * [Grid Fields](#grid-fields) * [Methods](#methods) * [Callbacks](#callbacks) * [Grid Controller](#grid-controller) * [Validation](#validation) * [Localization](#localization) * [Sorting Strategies](#sorting-strategies) * [Load Strategies](#load-strategies) * [Load Indication](#load-indication) * [Requirement](#requirement) * [Compatibility](#compatibility) ## Demos See [Demos](http://js-grid.com/demos/) on project site. Sample projects showing how to use jsGrid with the most popular backend technologies * **PHP** - https://github.com/tabalinas/jsgrid-php * **ASP.NET WebAPI** - https://github.com/tabalinas/jsgrid-webapi * **Express (NodeJS)** - https://github.com/tabalinas/jsgrid-express * **Ruby on Rail** - https://github.com/tabalinas/jsgrid-rails * **Django (Python)** - https://github.com/tabalinas/jsgrid-django ## Installation Install jsgrid with bower: ```bash $ bower install js-grid --save ``` Find jsGrid cdn links [here](https://cdnjs.com/libraries/jsgrid). ## Basic Usage Ensure that jQuery library of version 1.8.3 or later is included. Include `jsgrid.min.js`, `jsgrid-theme.min.css`, and `jsgrid.min.css` files into the web page. Create grid applying jQuery plugin `jsGrid` with grid config as follows: ```javascript $("#jsGrid").jsGrid({ width: "100%", height: "400px", filtering: true, editing: true, sorting: true, paging: true, data: db.clients, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] }); ``` ## Configuration The config object may contain following options (default values are specified below): ```javascript { fields: [], data: [], autoload: false, controller: { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, width: "auto", height: "auto", heading: true, filtering: false, inserting: false, editing: false, selecting: true, sorting: false, paging: false, pageLoading: false, insertRowLocation: "bottom", rowClass: function(item, itemIndex) { ... }, rowClick: function(args) { ... }, rowDoubleClick: function(args) { ... }, noDataContent: "Not found", confirmDeleting: true, deleteConfirm: "Are you sure?", pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", invalidNotify: function(args) { ... } invalidMessage: "Invalid data entered!", loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, loadIndicator: function(config) { ... } loadStrategy: function(config) { ... } updateOnResize: true, rowRenderer: null, headerRowRenderer: null, filterRowRenderer: null, insertRowRenderer: null, editRowRenderer: null, pagerRenderer: null } ``` ### fields An array of fields (columns) of the grid. Each field has general options and specific options depending on field type. General options peculiar to all field types: ```javascript { type: "", name: "", title: "", align: "", width: 100, visible: true, css: "", headercss: "", filtercss: "", insertcss: "", editcss: "", filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", headerTemplate: function() { ... }, itemTemplate: function(value, item) { ... }, filterTemplate: function() { ... }, insertTemplate: function() { ... }, editTemplate: function(value, item) { ... }, filterValue: function() { ... }, insertValue: function() { ... }, editValue: function() { ... }, cellRenderer: null, validate: null } ``` - **type** is a string key of field (`"text"|"number"|"checkbox"|"select"|"textarea"|"control"`) in fields registry `jsGrid.fields` (the registry can be easily extended with custom field types). - **name** is a property of data item associated with the column. - **title** is a text to be displayed in the header of the column. If `title` is not specified, the `name` will be used instead. - **align** is alignment of text in the cell. Accepts following values `"left"|"center"|"right"`. - **width** is a width of the column. - **visible** is a boolean specifying whether to show a column or not. (version added: 1.3) - **css** is a string representing css classes to be attached to the table cell. - **headercss** is a string representing css classes to be attached to the table header cell. If not specified, then **css** is attached instead. - **filtercss** is a string representing css classes to be attached to the table filter row cell. If not specified, then **css** is attached instead. - **insertcss** is a string representing css classes to be attached to the table insert row cell. If not specified, then **css** is attached instead. - **editcss** is a string representing css classes to be attached to the table edit row cell. If not specified, then **css** is attached instead. - **filtering** is a boolean specifying whether or not column has filtering (`filterTemplate()` is rendered and `filterValue()` is included in load filter object). - **inserting** is a boolean specifying whether or not column has inserting (`insertTemplate()` is rendered and `insertValue()` is included in inserting item). - **editing** is a boolean specifying whether or not column has editing (`editTemplate()` is rendered and `editValue()` is included in editing item). - **sorting** is a boolean specifying whether or not column has sorting ability. - **sorter** is a string or a function specifying how to sort item by the field. The string is a key of sorting strategy in the registry `jsGrid.sortStrategies` (the registry can be easily extended with custom sorting functions). Sorting function has the signature `function(value1, value2) { return -1|0|1; }`. - **headerTemplate** is a function to create column header content. It should return markup as string, DomNode or jQueryElement. - **itemTemplate** is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterTemplate** is a function to create filter row cell content. It should return markup as string, DomNode or jQueryElement. - **insertTemplate** is a function to create insert row cell content. It should return markup as string, DomNode or jQueryElement. - **editTemplate** is a function to create cell content of editing row. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterValue** is a function returning the value of filter property associated with the column. - **insertValue** is a function returning the value of inserting item property associated with the column. - **editValue** is a function returning the value of editing item property associated with the column. - **cellRenderer** is a function to customize cell rendering. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. The function should return markup as a string, jQueryElement or DomNode representing table cell `td`. - **validate** is a string as validate rule name or validation function or a validation configuration object or an array of validation configuration objects. Read more details about validation in the [Validation section](#validation). Specific field options depends on concrete field type. Read about build-in fields in [Grid Fields](#grid-fields) section. ### data An array of items to be displayed in the grid. The option should be used to provide static data. Use the `controller` option to provide non static data. ### autoload (default `false`) A boolean value specifying whether `controller.loadData` will be called when grid is rendered. ### controller An object or function returning an object with the following structure: ```javascript { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop } ``` - **loadData** is a function returning an array of data or jQuery promise that will be resolved with an array of data (when `pageLoading` is `true` instead of object the structure `{ data: [items], itemsCount: [total items count] }` should be returned). Accepts filter parameter including current filter options and paging parameters when `pageLoading` is `true`. - **insertItem** is a function returning inserted item or jQuery promise that will be resolved with inserted item. Accepts inserting item object. - **updateItem** is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object. - **deleteItem** is a function deleting item. Returns jQuery promise that will be resolved when deletion is completed. Accepts deleting item object. Read more about controller interface in [Grid Controller](#grid-controller) section. ### width (default: `"auto"`) Specifies the overall width of the grid. Accepts all value types accepting by `jQuery.width`. ### height (default: `"auto"`) Specifies the overall height of the grid including the pager. Accepts all value types accepting by `jQuery.height`. ### heading (default: `true`) A boolean value specifies whether to show grid header or not. ### filtering (default: `false`) A boolean value specifies whether to show filter row or not. ### inserting (default: `false`) A boolean value specifies whether to show inserting row or not. ### editing (default: `false`) A boolean value specifies whether editing is allowed. ### selecting (default: `true`) A boolean value specifies whether to highlight grid rows on hover. ### sorting (default: `false`) A boolean value specifies whether sorting is allowed. ### paging (default: `false`) A boolean value specifies whether data is displayed by pages. ### pageLoading (default: `false`) A boolean value specifies whether to load data by page. When `pageLoading` is `true` the `loadData` method of controller accepts `filter` parameter with two additional properties `pageSize` and `pageIndex`. ### insertRowLocation (default: `"bottom"`) Specifies the location of an inserted row within the grid. When `insertRowLocation` is `"bottom"` the new row will appear at the bottom of the grid. When set to `"top"`, the new row will appear at the top. ### rowClass A string or a function specifying row css classes. A string contains classes separated with spaces. A function has signature `function(item, itemIndex)`. It accepts the data item and index of the item. It should returns a string containing classes separated with spaces. ### rowClick A function handling row click. Accepts single argument with following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` By default `rowClick` performs row editing when `editing` is `true`. ### rowDoubleClick A function handling row double click. Accepts single argument with the following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` ### noDataContent (default `"Not found"`) A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when `data` is an empty array. ### confirmDeleting (default `true`) A boolean value specifying whether to ask user to confirm item deletion. ### deleteConfirm (default `"Are you sure?"`) A string or a function returning string specifying delete confirmation message to be displayed to the user. A function has the signature `function(item)` and accepts item to be deleted. ### pagerContainer (default `null`) A jQueryElement or DomNode to specify where to render a pager. Used for external pager rendering. When it is equal to `null`, the pager is rendered at the bottom of the grid. ### pageIndex (default `1`) An integer value specifying current page index. Applied only when `paging` is `true`. ### pageSize (default `20`) An integer value specifying the amount of items on the page. Applied only when `paging` is `true`. ### pageButtonCount (default `15`) An integer value specifying the maximum amount of page buttons to be displayed in the pager. ### pagerFormat A string specifying pager format. The default value is `"Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}"` There are placeholders that can be used in the format: ```javascript {first} // link to first page {prev} // link to previous page {pages} // page links {next} // link to next page {last} // link to last page {pageIndex} // current page index {pageCount} // total amount of pages {itemCount} // total amount of items ``` ### pageNextText (default `"Next"`) A string specifying the text of the link to the next page. ### pagePrevText (default `"Prev"`) A string specifying the text of the link to the previous page. ### pageFirstText (default `"First"`) A string specifying the text of the link to the first page. ### pageLastText (default `"Last"`) A string specifying the text of the link to the last page. ### pageNavigatorNextText (default `"..."`) A string specifying the text of the link to move to next set of page links, when total amount of pages more than `pageButtonCount`. ### pageNavigatorPrevText (default `"..."`) A string specifying the text of the link to move to previous set of page links, when total amount of pages more than `pageButtonCount`. ### invalidMessage (default `"Invalid data entered!"`) A string specifying the text of the alert message, when invalid data was entered. ### invalidNotify A function triggered, when invalid data was entered. By default all violated validators messages are alerted. The behavior can be customized by providing custom function. The function accepts a single argument with the following structure: ```javascript { item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` In the following example error messages are printed in the console instead of alerting: ```javascript $("#grid").jsGrid({ ... invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.field + ": " + error.message; }); console.log(messages); } ... }); ``` ### loadIndication (default `true`) A boolean value specifying whether to show loading indication during controller operations execution. ### loadIndicationDelay (default `500`) An integer value specifying the delay in ms before showing load indication. Applied only when `loadIndication` is `true`. ### loadMessage (default `"Please, wait..."`) A string specifying the text of loading indication panel. Applied only when `loadIndication` is `true`. ### loadShading (default `true`) A boolean value specifying whether to show overlay (shader) over grid content during loading indication. Applied only when `loadIndication` is `true`. ### loadIndicator An object or a function returning an object representing grid load indicator. Load indicator could be any js object supporting two methods `show` and `hide`. `show` is called on each loading start. `hide` method is called on each loading finish. Read more about custom load indicator in the [Load Indication](#load-indication) section. ### loadStrategy An object or a function returning an object representing grid load strategy. Load strategy defines behavior of the grid after loading data (any interaction with grid controller methods including data manipulation like inserting, updating and removing). There are two build-in load strategies: `DirectLoadingStrategy` and `PageLoadingStrategy`. Load strategy depends on `pageLoading` option value. For advanced scenarios custom load strategy can be provided. Read more about custom load strategies in the [Load Strategies](#load-strategies) section. ### updateOnResize (default `true`) A boolean value specifying whether to refresh grid on window resize event. ### rowRenderer (default `null`) A function to customize row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### headerRowRenderer (default `null`) A function to customize grid header row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### filterRowRenderer (default `null`) A function to customize grid filter row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### insertRowRenderer (default `null`) A function to customize grid inserting row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### editRowRenderer (default `null`) A function to customize editing row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### pagerRenderer (default `null`) > version added: 1.2 A function to customize pager rendering. The function accepts a single argument with the following structure: ```javascript { pageIndex, // index of the currently opened page pageCount // total amount of grid pages } ``` The function should return markup as a string, jQueryElement or DomNode representing the pager. If `pagerRenderer` is specified, then `pagerFormat` option will be ignored. ## Grid Fields All fields supporting by grid are stored in `jsGrid.fields` object, where key is a type of the field and the value is the field class. `jsGrid.fields` contains following build-in fields: ```javascript { text: { ... }, // simple text input number: { ... }, // number input select: { ... }, // select control checkbox: { ... }, // checkbox input textarea: { ... }, // textarea control (renders textarea for inserting and editing and text input for filtering) control: { ... } // control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row } ``` Each build-in field can be easily customized with general configuration properties described in [fields](#fields) section and custom field-specific properties described below. ### text Text field renders `<input type="text">` in filter, inserting and editing rows. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### number Number field renders `<input type="number">` in filter, inserting and editing rows. Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "right", // right text alignment readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### select Select field renders `<select>` control in filter, inserting and editing rows. Custom properties: ```javascript { align: "center", // center text alignment autosearch: true, // triggers searching when the user changes the selected item in the filter items: [], // an array of items for select valueField: "", // name of property of item to be used as value textField: "", // name of property of item to be used as displaying value selectedIndex: -1, // index of selected item by default valueType: "number|string", // the data type of the value readOnly: false // a boolean defines whether select is readonly (added in v1.4) } ``` If valueField is not defined, then the item index is used instead. If textField is not defined, then item itself is used to display value. For instance the simple select field config may look like: ```javascript { name: "Country", type: "select", items: [ "", "United States", "Canada", "United Kingdom" ] } ``` or more complex with items as objects: ```javascript { name: "Country", type: "select" items: [ { Name: "", Id: 0 }, { Name: "United States", Id: 1 }, { Name: "Canada", Id: 2 }, { Name: "United Kingdom", Id: 3 } ], valueField: "Id", textField: "Name" } ``` `valueType` defines whether the field value should be converted to a number or returned as a string. The value of the option is determined automatically depending on the data type of `valueField` of the first item, but it can be overridden. ### checkbox Checkbox field renders `<input type="checkbox">` in filter, inserting and editing rows. Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "center", // center text alignment autosearch: true // triggers searching when the user clicks checkbox in filter } ``` ### textarea Textarea field renders `<textarea>` in inserting and editing rows and `<input type="text">` in filter row. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether textarea is readonly (added in v1.4) } ``` ### control Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. It also renders button switching between filtering and searching in header row. Custom properties: ```javascript { editButton: true, // show edit button deleteButton: true, // show delete button clearFilterButton: true, // show clear filter button modeSwitchButton: true, // show switching filtering/inserting button align: "center", // center content alignment width: 50, // default column width is 50px filtering: false, // disable filtering for column inserting: false, // disable inserting for column editing: false, // disable editing for column sorting: false, // disable sorting for column searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode editButtonTooltip: "Edit", // tooltip of edit item button deleteButtonTooltip: "Delete", // tooltip of delete item button searchButtonTooltip: "Search", // tooltip of search button clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button insertButtonTooltip: "Insert", // tooltip of insert button updateButtonTooltip: "Update", // tooltip of update item button cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button } ``` ### Custom Field If you need a completely custom field, the object `jsGrid.fields` can be easily extended. In this example we define new grid field `date`: ```javascript var MyDateField = function(config) { jsGrid.Field.call(this, config); }; MyDateField.prototype = new jsGrid.Field({ css: "date-field", // redefine general property 'css' align: "center", // redefine general property 'align' myCustomProperty: "foo", // custom property sorter: function(date1, date2) { return new Date(date1) - new Date(date2); }, itemTemplate: function(value) { return new Date(value).toDateString(); }, insertTemplate: function(value) { return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); }, editTemplate: function(value) { return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); }, insertValue: function() { return this._insertPicker.datepicker("getDate").toISOString(); }, editValue: function() { return this._editPicker.datepicker("getDate").toISOString(); } }); jsGrid.fields.date = MyDateField; ``` To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. Here `itemTemplate` just returns the string representation of a date. `insertTemplate` and `editTemplate` create jQuery UI datePicker for inserting and editing row. Of course jquery ui library should be included to make it work. `insertValue` and `editValue` return date to insert and update items accordingly. We also defined date specific sorter. Now, our new field `date` can be used in the grid config as follows: ```javascript { fields: [ ... { type: "date", myCustomProperty: "bar" }, ... ] } ``` ## Methods jsGrid methods could be called with `jsGrid` jQuery plugin or directly. To use jsGrid plugin to call a method, just call `jsGrid` with method name and required parameters as next arguments: ```javascript // calling method with jQuery plugin $("#grid").jsGrid("methodName", param1, param2); ``` To call method directly you need to retrieve grid instance or just create grid with the constructor: ```javascript // retrieve grid instance from element data var grid = $("#grid").data("JSGrid"); // create grid with the constructor var grid = new jsGrid.Grid($("#grid"), { ... }); // call method directly grid.methodName(param1, param2); ``` ### cancelEdit() Cancels row editing. ```javascript $("#grid").jsGrid("cancelEdit"); ``` ### clearFilter(): `Promise` Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed. ```javascript $("#grid").jsGrid("clearFilter").done(function() { console.log("filtering completed"); }); ``` ### clearInsert() Clears current inserting row. ```javascript $("#grid").jsGrid("clearInsert"); ``` ### deleteItem(item|$row|rowNode): `Promise` Removes specified row from the grid. Returns jQuery promise resolved when deletion is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // delete row by item reference $("#grid").jsGrid("deleteItem", item); // delete row by jQueryElement $("#grid").jsGrid("deleteItem", $(".specific-row")); // delete row by DomNode $("#grid").jsGrid("deleteItem", rowNode); ``` ### destroy() Destroys the grid and brings the Node to its original state. ```javascript $("#grid").jsGrid("destroy"); ``` ### editItem(item|$row|rowNode) Sets grid editing row. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // edit row by item reference $("#grid").jsGrid("editItem", item); // edit row by jQueryElement $("#grid").jsGrid("editItem", $(".specific-row")); // edit row by DomNode $("#grid").jsGrid("editItem", rowNode); ``` ### getFilter(): `Object` Get grid filter as a plain object. ```javascript var filter = $("#grid").jsGrid("getFilter"); ``` ### getSorting(): `Object` > version added: 1.2 Get grid current sorting params as a plain object with the following format: ```javascript { field, // the name of the field by which grid is sorted order // 'asc' or 'desc' depending on sort order } ``` ```javascript var sorting = $("#grid").jsGrid("getSorting"); ``` ### fieldOption(fieldName|fieldIndex, optionName, [optionValue]) > version added: 1.3 Gets or sets the value of a field option. **fieldName|fieldIndex** is the name or the index of the field to get/set the option value (if the grid contains more than one field with the same name, the first field will be used). **optionName** is the name of the field option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the field option `optionName` will be returned. ```javascript // hide the field "ClientName" $("#grid").jsGrid("fieldOption", "ClientName", "visible", false); // get width of the 2nd field var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width"); ``` ### insertItem([item]): `Promise` Inserts row into the grid based on item. Returns jQuery promise resolved when insertion is completed. **item** is the item to pass to `controller.insertItem`. If `item` is not specified the data from inserting row will be inserted. ```javascript // insert item from inserting row $("#grid").jsGrid("insertItem"); // insert item $("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() { console.log("insertion completed"); }); ``` ### loadData([filter]): `Promise` Loads data calling corresponding `controller.loadData` method. Returns jQuery promise resolved when data loading is completed. It preserves current sorting and paging unlike the `search` method . **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // load data with current grid filter $("#grid").jsGrid("loadData"); // loadData with custom filter $("#grid").jsGrid("loadData", { Name: "John" }).done(function() { console.log("data loaded"); }); ``` ### exportData([options]) Transforms the grid data into the specified output type. Output can be formatted, filtered or modified by providing options. Currently only supports CSV output. ```javascript //Basic export var csv = $("#grid").jsGrid("exportData"); //Full Options var csv = $("#grid").jsGrid("exportData", { type: "csv", //Only CSV supported subset: "all" | "visible", //Visible will only output the currently displayed page delimiter: "|", //If using csv, the character to seperate fields includeHeaders: true, //Include header row in output encapsulate: true, //Surround each field with qoutation marks; needed for some systems newline: "\r\n", //Newline character to use //Takes each item and returns true if it should be included in output. //Executed only on the records within the given subset above. filter: function(item){return true}, //Transformations are a way to modify the display value of the output. //Provide a key of the field name, and a function that takes the current value. transformations: { "Married": function(value){ if (value === true){ return "Yes" } else{ return "No" } } } }); ``` ### openPage(pageIndex) Opens the page of specified index. **pageIndex** is one-based index of the page to open. The value should be in range from 1 to [total amount of pages]. ### option(optionName, [optionValue]) Gets or sets the value of an option. **optionName** is the name of the option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the option `optionName` will be returned. ```javascript // turn off paging $("#grid").jsGrid("option", "paging", false); // get current page index var pageIndex = $("#grid").jsGrid("option", "pageIndex"); ``` ### refresh() Refreshes the grid. Renders the grid body and pager content, recalculates sizes. ```javascript $("#grid").jsGrid("refresh"); ``` ### render(): `Promise` Performs complete grid rendering. If option `autoload` is `true` calls `controller.loadData`. The state of the grid like current page and sorting is retained. Returns jQuery promise resolved when data loading is completed. If auto-loading is disabled the promise is instantly resolved. ```javascript $("#grid").jsGrid("render").done(function() { console.log("rendering completed and data loaded"); }); ``` ### reset() Resets the state of the grid. Goes to the first data page, resets sorting, and then calls `refresh`. ```javascript $("#grid").jsGrid("reset"); ``` ### rowByItem(item): `jQueryElement` > version added: 1.3 Gets the row jQuery element corresponding to the item. **item** is the item corresponding to the row. ```javascript var $row = $("#grid").jsGrid("rowByItem", item); ``` ### search([filter]): `Promise` Performs filtering of the grid. Returns jQuery promise resolved when data loading is completed. It resets current sorting and paging unlike the `loadData` method. **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // search with current grid filter $("#grid").jsGrid("search"); // search with custom filter $("#grid").jsGrid("search", { Name: "John" }).done(function() { console.log("filtering completed"); }); ``` ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showPrevPages"); ``` ### showNextPages() Shows next set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ```` ### insertItem(item): `Promise|insertedItem` Called on item insertion. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid ## Sorting Strategies Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: function() { ... } // called on loading finish } ``` This simple example prints messages to console instead of showing load indicator: ```javascript { loadIndicator: { show: function() { console.log("loading started"); }, hide: function() { console.log("loading finished"); } } } ``` If `loadIndicator` is a function, it accepts the config of load indicator in the following format: ```javascript { container, // grid container div message, // the loading message is a value of the option loadMessage shading // the boolean value defining whether to show shading. This is a value of the option loadShading } ``` The similar example printing messages to console shows how to configure loading indicator with a function returning an object: ```javascript { loadIndicator: function(config) { return { show: function() { console.log("loading started: " + config.message); }, hide: function() { console.log("loading finished"); } }; } } ``` Customization of loading indicator is useful, when you want to use any external load indicator that is used for all other ajax requests on the page. This example shows how to use [spin.js](http://fgnass.github.io/spin.js/) to indicate loading: ```javascript { loadIndicator: function(config) { var container = config.container[0]; var spinner = new Spinner(); return { show: function() { spinner.spin(container); }, hide:
74
Docs: Sorting strategies descirption
1
.md
md
mit
tabalinas/jsgrid
10062333
<NME> README.md <BEF> # FruitMachine [![Build Status](https://travis-ci.org/ftlabs/fruitmachine.png?branch=master)](https://travis-ci.org/ftlabs/fruitmachine) A lightweight component layout engine for client and server. ```js // Define a module var Apple = fruitmachine.define({ name: 'apple', template: function(){ return 'hello' } }); // Create a module var apple = new Apple(); // Render it apple.render(); apple.el.outerHTML; //=> <div class="apple">hello</div> ``` ## Installation ``` $ npm install fruitmachine ``` or ``` $ bower install fruitmachine ``` or Download the [pre-built version][built] (~2k gzipped). [built]: http://wzrd.in/standalone/fruitmachine@latest ## Examples - [Article viewer](http://ftlabs.github.io/fruitmachine/examples/article-viewer/) - [TODO](http://ftlabs.github.io/fruitmachine/examples/todo/) ## Documentation - [Introduction](docs/introduction.md) - [Getting started](docs/getting-started.md) - [Defining modules](docs/defining-modules.md) - [Slots](docs/slots.md) - [View assembly](docs/layout-assembly.md) - [Instantiation](docs/module-instantiation.md) - [Templates](docs/templates.md) - [Template markup](docs/template-markup.md) - [Rendering](docs/rendering.md) - [DOM injection](docs/injection.md) - [The module element](docs/module-el.md) - [Queries](docs/queries.md) - [Helpers](docs/module-helpers.md) - [Removing & destroying](docs/removing-and-destroying.md) - [Extending](docs/extending-modules.md) - [Server-side rendering](docs/server-side-rendering.md) - [API](docs/api.md) - [Events](docs/events.md) ## Tests #### With PhantomJS ``` $ npm install $ npm test ``` #### Without PhantomJS ``` $ node_modules/.bin/buster-static ``` ...then visit http://localhost:8282/ in browser ## Author - **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage) ## Contributors - **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage) - **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews) ## License Copyright (c) 2018 The Financial Times Limited Licensed under the MIT license. ## Credits and collaboration The lead developer of FruitMachine is [Wilson Page](http://github.com/wilsonpage) at FT Labs. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. Enjoy... <MSG> Buster busted <DFF> @@ -1,4 +1,5 @@ -# FruitMachine [![Build Status](https://travis-ci.org/ftlabs/fruitmachine.png?branch=master)](https://travis-ci.org/ftlabs/fruitmachine) +# FruitMachine +<!--[![Build Status](https://travis-ci.org/ftlabs/fruitmachine.png?branch=master)](https://travis-ci.org/ftlabs/fruitmachine)--> A lightweight component layout engine for client and server. @@ -96,4 +97,4 @@ Licensed under the MIT license. ## Credits and collaboration -The lead developer of FruitMachine is [Wilson Page](http://github.com/wilsonpage) at FT Labs. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. Enjoy... \ No newline at end of file +The lead developer of FruitMachine is [Wilson Page](http://github.com/wilsonpage) at FT Labs. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. Enjoy...
3
Buster busted
2
.md
md
mit
ftlabs/fruitmachine
10062334
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062335
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062336
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062337
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062338
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062339
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062340
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062341
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062342
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062343
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062344
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062345
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062346
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062347
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062348
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } } } private sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); return new Size(width, _element.Text.Height); } public override Rect ComputeBoundingBox() public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Fixed TabGlyphRun bounding box <DFF> @@ -142,7 +142,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabTextElement : VisualLineElement + internal sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; @@ -175,7 +175,7 @@ namespace AvaloniaEdit.Rendering } } - private sealed class TabGlyphRun : TextEmbeddedObject + internal sealed class TabGlyphRun : TextEmbeddedObject { private readonly TabTextElement _element; @@ -195,8 +195,9 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - var width = Math.Min(0, _element.Text.WidthIncludingTrailingWhitespace - 1); - return new Size(width, _element.Text.Height); + return new Size( + _element.Text.WidthIncludingTrailingWhitespace, + _element.Text.Height); } public override Rect ComputeBoundingBox() @@ -206,7 +207,6 @@ namespace AvaloniaEdit.Rendering public override void Draw(DrawingContext drawingContext, Point origin) { - origin = origin.WithY(origin.Y - _element.Text.Baseline); _element.Text.Draw(drawingContext, origin); } }
5
Fixed TabGlyphRun bounding box
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062349
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.LineCountChanged += DocumentOnLineCountChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { int count = _document.Lines.Count; if (_lineRanges != null) ArrayPool<LineRange>.Shared.Return(_lineRanges); _lineRanges = ArrayPool<LineRange>.Shared.Rent(count); for (int i = 0; i < count; i++) { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; if (_lineRanges != null) private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } } } private void DocumentOnLineCountChanged(object sender, EventArgs e) { try { lock (_lock) { _lineCount = _document.LineCount; } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try public override void UpdateLine(int lineIndex) { lock(_lock) { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Ensure we calculate the total lines at the same time the ranges are updated to avoid desync <DFF> @@ -36,7 +36,6 @@ namespace AvaloniaEdit.TextMate _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; - _document.LineCountChanged += DocumentOnLineCountChanged; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } @@ -52,13 +51,13 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { - int count = _document.Lines.Count; + _lineCount = _document.Lines.Count; if (_lineRanges != null) ArrayPool<LineRange>.Shared.Return(_lineRanges); - _lineRanges = ArrayPool<LineRange>.Shared.Rent(count); - for (int i = 0; i < count; i++) + _lineRanges = ArrayPool<LineRange>.Shared.Rent(_lineCount); + for (int i = 0; i < _lineCount; i++) { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; @@ -71,7 +70,6 @@ namespace AvaloniaEdit.TextMate { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; - _document.LineCountChanged -= DocumentOnLineCountChanged; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; if (_lineRanges != null) @@ -104,21 +102,6 @@ namespace AvaloniaEdit.TextMate } } - private void DocumentOnLineCountChanged(object sender, EventArgs e) - { - try - { - lock (_lock) - { - _lineCount = _document.LineCount; - } - } - catch (Exception ex) - { - _exceptionHandler?.Invoke(ex); - } - } - private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try @@ -187,7 +170,7 @@ namespace AvaloniaEdit.TextMate public override void UpdateLine(int lineIndex) { - lock(_lock) + lock (_lock) { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset;
4
Ensure we calculate the total lines at the same time the ranges are updated to avoid desync
21
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit