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
|
---|---|---|---|---|---|---|---|---|
10057850 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057851 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057852 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057853 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057854 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057855 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057856 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057857 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057858 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057859 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057860 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057861 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057862 | <NME> CompletionWindow.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 Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Media;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// The code completion window.
/// </summary>
public class CompletionWindow : CompletionWindowBase
{
private PopupWithCustomPosition _toolTip;
private ContentControl _toolTipContent;
/// <summary>
/// Gets the completion list used in this completion window.
/// </summary>
public CompletionList CompletionList { get; }
/// <summary>
/// Creates a new code completion window.
/// </summary>
public CompletionWindow(TextArea textArea) : base(textArea)
{
CompletionList = new CompletionList();
// keep height automatic
CloseAutomatically = true;
MaxHeight = 225;
Width = 175;
Child = CompletionList;
// prevent user from resizing window to 0x0
MinHeight = 15;
MinWidth = 30;
_toolTipContent = new ContentControl();
_toolTipContent.Classes.Add("ToolTip");
_toolTip = new PopupWithCustomPosition
{
IsLightDismissEnabled = true,
PlacementTarget = this,
PlacementMode = PlacementMode.Right,
Child = _toolTipContent,
};
LogicalChildren.Add(_toolTip);
//_toolTip.Closed += (o, e) => ((Popup)o).Child = null;
AttachEvents();
}
protected override void OnClosed()
{
base.OnClosed();
if (_toolTip != null)
{
_toolTip.IsOpen = false;
_toolTip = null;
_toolTipContent = null;
}
}
#region ToolTip handling
private void CompletionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_toolTipContent == null) return;
var item = CompletionList.SelectedItem;
var description = item?.Description;
if (description != null)
{
if (description is string descriptionText)
{
_toolTipContent.Content = new TextBlock
{
Text = descriptionText,
TextWrapping = TextWrapping.Wrap
};
}
else
};
}
else
{
_toolTipContent.Content = description;
}
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
_toolTip.Offset = new PixelPoint(2, index * 20);
}
_toolTip.IsOpen = true;
}
_toolTip.PlacementTarget = this.Host as PopupRoot;
_toolTip.IsOpen = true;
}
else
{
_toolTip.IsOpen = false;
}
}
#endregion
private void CompletionList_InsertionRequested(object sender, EventArgs e)
{
Hide();
// The window must close before Complete() is called.
// If the Complete callback pushes stacked input handlers, we don't want to pop those when the CC window closes.
var item = CompletionList.SelectedItem;
item?.Complete(TextArea, new AnchorSegment(TextArea.Document, StartOffset, EndOffset - StartOffset), e);
}
private void AttachEvents()
{
CompletionList.InsertionRequested += CompletionList_InsertionRequested;
CompletionList.SelectionChanged += CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged += CaretPositionChanged;
TextArea.PointerWheelChanged += TextArea_MouseWheel;
TextArea.TextInput += TextArea_PreviewTextInput;
}
/// <inheritdoc/>
protected override void DetachEvents()
{
CompletionList.InsertionRequested -= CompletionList_InsertionRequested;
CompletionList.SelectionChanged -= CompletionList_SelectionChanged;
TextArea.Caret.PositionChanged -= CaretPositionChanged;
TextArea.PointerWheelChanged -= TextArea_MouseWheel;
TextArea.TextInput -= TextArea_PreviewTextInput;
base.DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled)
{
CompletionList.HandleKey(e);
}
}
private void TextArea_PreviewTextInput(object sender, TextInputEventArgs e)
{
e.Handled = RaiseEventPair(this, null, TextInputEvent,
new TextInputEventArgs { Device = e.Device, Text = e.Text });
}
private void TextArea_MouseWheel(object sender, PointerWheelEventArgs e)
{
e.Handled = RaiseEventPair(GetScrollEventTarget(),
null, PointerWheelChangedEvent, e);
}
private Control GetScrollEventTarget()
{
if (CompletionList == null)
return this;
return CompletionList.ScrollViewer ?? CompletionList.ListBox ?? (Control)CompletionList;
}
/// <summary>
/// Gets/Sets whether the completion window should close automatically.
/// The default value is true.
/// </summary>
public bool CloseAutomatically { get; set; }
/// <inheritdoc/>
protected override bool CloseOnFocusLost => CloseAutomatically;
/// <summary>
/// When this flag is set, code completion closes if the caret moves to the
/// beginning of the allowed range. This is useful in Ctrl+Space and "complete when typing",
/// but not in dot-completion.
/// Has no effect if CloseAutomatically is false.
/// </summary>
public bool CloseWhenCaretAtBeginning { get; set; }
private void CaretPositionChanged(object sender, EventArgs e)
{
var offset = TextArea.Caret.Offset;
if (offset == StartOffset)
{
if (CloseAutomatically && CloseWhenCaretAtBeginning)
{
Hide();
}
else
{
CompletionList.SelectItem(string.Empty);
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
return;
}
if (offset < StartOffset || offset > EndOffset)
{
if (CloseAutomatically)
{
Hide();
}
}
else
{
var document = TextArea.Document;
if (document != null)
{
CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset));
if (CompletionList.ListBox.ItemCount == 0) IsVisible = false;
else IsVisible = true;
}
}
}
}
}
<MSG> style improvement
<DFF> @@ -107,7 +107,7 @@ namespace AvaloniaEdit.CodeCompletion
};
}
else
- {
+ {
_toolTipContent.Content = description;
}
@@ -117,7 +117,7 @@ namespace AvaloniaEdit.CodeCompletion
if (CompletionList.CurrentList != null)
{
int index = CompletionList.CurrentList.IndexOf(item);
- _toolTip.Offset = new PixelPoint(2, index * 20);
+ _toolTip.Offset = new PixelPoint(2, index * 20); //Todo find way to measure item height
}
_toolTip.IsOpen = true;
}
| 2 | style improvement | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057863 | <NME> LumenPassport.php
<BEF> <?php
namespace Dusterio\LumenPassport;
use Illuminate\Support\Arr;
use Laravel\Passport\Passport;
use DateTimeInterface;
use Carbon\Carbon;
use Laravel\Lumen\Application;
use Laravel\Lumen\Routing\Router;
class LumenPassport
{
/**
* Allow simultaneous logins for users
*
* @var bool
*/
public static $allowMultipleTokens = false;
/**
* The date when access tokens expire (specific per password client).
*
* @var array
*/
public static $tokensExpireAt = [];
/**
* Instruct Passport to keep revoked tokens pruned.
*/
public static function allowMultipleTokens()
{
static::$allowMultipleTokens = true;
}
/**
* Get or set when access tokens expire.
*
* @param \DateTimeInterface|null $date
* @param int $clientId
* @return \DateInterval|static
*/
public static function tokensExpireIn(DateTimeInterface $date = null, $clientId = null)
{
if (! $clientId) return Passport::tokensExpireIn($date);
if (is_null($date)) {
return isset(static::$tokensExpireAt[$clientId])
? Carbon::now()->diff(static::$tokensExpireAt[$clientId])
: Passport::tokensExpireIn();
} else {
static::$tokensExpireAt[$clientId] = $date;
}
return new static;
}
/**
* Get a Passport route registrar.
*
* @param callable|Router|Application $callback
* @param array $options
* @return RouteRegistrar
*/
public static function routes($callback = null, array $options = [])
{
if ($callback instanceof Application && preg_match('/(5\.[5-8]\..*)|(6\..*)|(7\..*)/', $callback->version())) $callback = $callback->router;
$callback = $callback ?: function ($router) {
$router->all();
};
$defaultOptions = [
'prefix' => 'oauth',
'namespace' => '\Laravel\Passport\Http\Controllers',
];
$options = array_merge($defaultOptions, $options);
$callback->group(Arr::except($options, ['namespace']), function ($router) use ($callback, $options) {
$routes = new RouteRegistrar($router, $options);
$routes->all();
});
}
}
<MSG> r lumen 8
<DFF> @@ -64,7 +64,7 @@ class LumenPassport
*/
public static function routes($callback = null, array $options = [])
{
- if ($callback instanceof Application && preg_match('/(5\.[5-8]\..*)|(6\..*)|(7\..*)/', $callback->version())) $callback = $callback->router;
+ if ($callback instanceof Application && preg_match('/(5\.[5-8]\..*)|(6\..*)|(7\..*)|(8\..*)/', $callback->version())) $callback = $callback->router;
$callback = $callback ?: function ($router) {
$router->all();
| 1 | r lumen 8 | 1 | .php | php | mit | dusterio/lumen-passport |
10057864 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057865 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057866 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057867 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057868 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057869 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057870 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057871 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057872 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057873 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057874 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057875 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057876 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057877 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057878 | <NME> text.log
<BEF> ADDFILE
<MSG> Add missing sample file to source control (it was ignored by git)
<DFF> @@ -0,0 +1,30 @@
+03/22 08:51:01 INFO :.main: *************** RSVP Agent started ***************
+03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf
+03/22 08:51:01 INFO :.main: Using log level 511
+03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket.
+03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS
+03/22 08:51:02 INFO :..reg_process: registering process with the system
+03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration
+03/22 08:51:02 INFO :..reg_process: return from registration rc=0
+03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7
+03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0
+03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1
+03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2
+03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3
+03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4
+03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5
+03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0
+03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer
+03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp
+03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP
+03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available.
+03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp
+03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and
\ No newline at end of file
| 30 | Add missing sample file to source control (it was ignored by git) | 0 | .log | Demo/Resources/SampleFiles/text | mit | AvaloniaUI/AvaloniaEdit |
10057879 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057880 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057881 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057882 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057883 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057884 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057885 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057886 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057887 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057888 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057889 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057890 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057891 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057892 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057893 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> reverse lineheight fix.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
+ return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | reverse lineheight fix. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057894 | <NME> README.md
<BEF> # FruitMachine
A lightweight modular layout engine for client and server. Currently powering the award winning FT Web App.
FruitMachine was designed to construct nested view layouts from strictly modular components. We wanted it to be as light and unopinionated as possible so that it could be applied to almost any layout problem.
```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
FruitMachine is largely unmaintained/finished. 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.
<MSG> Updated readme
<DFF> @@ -1,6 +1,6 @@
# FruitMachine
-A lightweight modular layout engine for client and server. Currently powering the award winning FT Web App.
+A lightweight modular layout engine for client and server. Currently powering the award winning [FT Web App](http://apps.ft.com/ftwebapp/).
FruitMachine was designed to construct nested view layouts from strictly modular components. We wanted it to be as light and unopinionated as possible so that it could be applied to almost any layout problem.
| 1 | Updated readme | 1 | .md | md | mit | ftlabs/fruitmachine |
10057895 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057896 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057897 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057898 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057899 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057900 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057901 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057902 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057903 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057904 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057905 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057906 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057907 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057908 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057909 | <NME> VisualLine.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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
using AvaloniaEdit.Document;
using AvaloniaEdit.Utils;
using LogicalDirection = AvaloniaEdit.Document.LogicalDirection;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// Represents a visual line in the document.
/// A visual line usually corresponds to one DocumentLine, but it can span multiple lines if
/// all but the first are collapsed.
/// </summary>
public sealed class VisualLine
{
public const int LENGTH_LIMIT = 3000;
private enum LifetimePhase : byte
{
Generating,
Transforming,
Live,
Disposed
}
private readonly TextView _textView;
private List<VisualLineElement> _elements;
internal bool HasInlineObjects;
private LifetimePhase _phase;
/// <summary>
/// Gets the document to which this VisualLine belongs.
/// </summary>
public TextDocument Document { get; }
/// <summary>
/// Gets the first document line displayed by this visual line.
/// </summary>
public DocumentLine FirstDocumentLine { get; }
/// <summary>
/// Gets the last document line displayed by this visual line.
/// </summary>
public DocumentLine LastDocumentLine { get; private set; }
/// <summary>
/// Gets a read-only collection of line elements.
/// </summary>
public ReadOnlyCollection<VisualLineElement> Elements { get; private set; }
private ReadOnlyCollection<TextLine> _textLines;
/// <summary>
/// Gets a read-only collection of text lines.
/// </summary>
public ReadOnlyCollection<TextLine> TextLines
{
get
{
if (_phase < LifetimePhase.Live)
throw new InvalidOperationException();
return _textLines;
}
}
/// <summary>
/// Gets the start offset of the VisualLine inside the document.
/// This is equivalent to <c>FirstDocumentLine.Offset</c>.
/// </summary>
public int StartOffset => FirstDocumentLine.Offset;
/// <summary>
/// Length in visual line coordinates.
/// </summary>
public int VisualLength { get; private set; }
/// <summary>
/// Length in visual line coordinates including the end of line marker, if TextEditorOptions.ShowEndOfLine is enabled.
/// </summary>
public int VisualLengthWithEndOfLineMarker
{
get
{
var length = VisualLength;
if (_textView.Options.ShowEndOfLine && LastDocumentLine.NextLine != null) length++;
return length;
}
}
/// <summary>
/// Gets the height of the visual line in device-independent pixels.
/// </summary>
public double Height { get; private set; }
/// <summary>
/// Gets the Y position of the line. This is measured in device-independent pixels relative to the start of the document.
/// </summary>
public double VisualTop { get; internal set; }
internal VisualLine(TextView textView, DocumentLine firstDocumentLine)
{
Debug.Assert(textView != null);
Debug.Assert(firstDocumentLine != null);
_textView = textView;
Document = textView.Document;
FirstDocumentLine = firstDocumentLine;
}
internal void ConstructVisualElements(ITextRunConstructionContext context, IReadOnlyList<VisualLineElementGenerator> generators)
{
Debug.Assert(_phase == LifetimePhase.Generating);
foreach (var g in generators)
{
g.StartGeneration(context);
}
_elements = new List<VisualLineElement>();
PerformVisualElementConstruction(generators);
foreach (var g in generators)
{
g.FinishGeneration();
}
var globalTextRunProperties = context.GlobalTextRunProperties;
foreach (var element in _elements)
{
element.SetTextRunProperties(new VisualLineElementTextRunProperties(globalTextRunProperties));
}
this.Elements = new ReadOnlyCollection<VisualLineElement>(_elements);
CalculateOffsets();
_phase = LifetimePhase.Transforming;
}
void PerformVisualElementConstruction(IReadOnlyList<VisualLineElementGenerator> generators)
{
var lineLength = FirstDocumentLine.Length;
var offset = FirstDocumentLine.Offset;
var currentLineEnd = offset + lineLength;
LastDocumentLine = FirstDocumentLine;
var askInterestOffset = 0; // 0 or 1
while (offset + askInterestOffset <= currentLineEnd)
{
var textPieceEndOffset = currentLineEnd;
foreach (var g in generators)
{
g.CachedInterest = g.GetFirstInterestedOffset(offset + askInterestOffset);
if (g.CachedInterest != -1)
{
if (g.CachedInterest < offset)
throw new ArgumentOutOfRangeException(g.GetType().Name + ".GetFirstInterestedOffset",
g.CachedInterest,
"GetFirstInterestedOffset must not return an offset less than startOffset. Return -1 to signal no interest.");
if (g.CachedInterest < textPieceEndOffset)
textPieceEndOffset = g.CachedInterest;
}
}
Debug.Assert(textPieceEndOffset >= offset);
if (textPieceEndOffset > offset)
{
var textPieceLength = textPieceEndOffset - offset;
_elements.Add(new VisualLineText(this, textPieceLength));
offset = textPieceEndOffset;
}
// If no elements constructed / only zero-length elements constructed:
// do not asking the generators again for the same location (would cause endless loop)
askInterestOffset = 1;
foreach (var g in generators)
{
if (g.CachedInterest == offset)
{
var element = g.ConstructElement(offset);
if (element != null)
{
_elements.Add(element);
if (element.DocumentLength > 0)
{
// a non-zero-length element was constructed
askInterestOffset = 0;
offset += element.DocumentLength;
if (offset > currentLineEnd)
{
var newEndLine = Document.GetLineByOffset(offset);
currentLineEnd = newEndLine.Offset + newEndLine.Length;
this.LastDocumentLine = newEndLine;
if (currentLineEnd < offset)
{
throw new InvalidOperationException(
"The VisualLineElementGenerator " + g.GetType().Name +
" produced an element which ends within the line delimiter");
}
}
break;
}
}
}
}
}
}
private void CalculateOffsets()
{
var visualOffset = 0;
var textOffset = 0;
foreach (var element in _elements)
{
element.VisualColumn = visualOffset;
element.RelativeTextOffset = textOffset;
visualOffset += element.VisualLength;
textOffset += element.DocumentLength;
}
VisualLength = visualOffset;
Debug.Assert(textOffset == LastDocumentLine.EndOffset - FirstDocumentLine.Offset);
}
internal void RunTransformers(ITextRunConstructionContext context, IReadOnlyList<IVisualLineTransformer> transformers)
{
Debug.Assert(_phase == LifetimePhase.Transforming);
foreach (var transformer in transformers)
{
transformer.Transform(context, _elements);
}
_phase = LifetimePhase.Live;
}
/// <summary>
/// Replaces the single element at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, params VisualLineElement[] newElements)
{
ReplaceElement(elementIndex, 1, newElements);
}
/// <summary>
/// Replaces <paramref name="count"/> elements starting at <paramref name="elementIndex"/> with the specified elements.
/// The replacement operation must preserve the document length, but may change the visual length.
/// </summary>
/// <remarks>
/// This method may only be called by line transformers.
/// </remarks>
public void ReplaceElement(int elementIndex, int count, params VisualLineElement[] newElements)
{
if (_phase != LifetimePhase.Transforming)
throw new InvalidOperationException("This method may only be called by line transformers.");
var oldDocumentLength = 0;
for (var i = elementIndex; i < elementIndex + count; i++)
{
oldDocumentLength += _elements[i].DocumentLength;
}
var newDocumentLength = 0;
foreach (var newElement in newElements)
{
newDocumentLength += newElement.DocumentLength;
}
if (oldDocumentLength != newDocumentLength)
throw new InvalidOperationException("Old elements have document length " + oldDocumentLength + ", but new elements have length " + newDocumentLength);
_elements.RemoveRange(elementIndex, count);
_elements.InsertRange(elementIndex, newElements);
CalculateOffsets();
}
internal void SetTextLines(List<TextLine> textLines)
{
_textLines = new ReadOnlyCollection<TextLine>(textLines);
Height = 0;
foreach (var line in textLines)
Height += line.Height;
}
/// <summary>
/// Gets the visual column from a document offset relative to the first line start.
/// </summary>
public int GetVisualColumn(int relativeTextOffset)
{
ThrowUtil.CheckNotNegative(relativeTextOffset, "relativeTextOffset");
foreach (var element in _elements)
{
if (element.RelativeTextOffset <= relativeTextOffset
&& element.RelativeTextOffset + element.DocumentLength >= relativeTextOffset)
{
return element.GetVisualColumn(relativeTextOffset);
}
}
return VisualLength;
}
/// <summary>
/// Gets the document offset (relative to the first line start) from a visual column.
/// </summary>
public int GetRelativeOffset(int visualColumn)
{
ThrowUtil.CheckNotNegative(visualColumn, "visualColumn");
var documentLength = 0;
foreach (var element in _elements)
{
if (element.VisualColumn <= visualColumn
&& element.VisualColumn + element.VisualLength > visualColumn)
{
return element.GetRelativeOffset(visualColumn);
}
documentLength += element.DocumentLength;
}
return documentLength;
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn)
{
return GetTextLine(visualColumn, false);
}
/// <summary>
/// Gets the text line containing the specified visual column.
/// </summary>
public TextLine GetTextLine(int visualColumn, bool isAtEndOfLine)
{
if (visualColumn < 0)
throw new ArgumentOutOfRangeException(nameof(visualColumn));
if (visualColumn >= VisualLengthWithEndOfLineMarker)
return TextLines[TextLines.Count - 1];
foreach (var line in TextLines)
{
if (isAtEndOfLine ? visualColumn <= line.Length : visualColumn < line.Length)
return line;
visualColumn -= line.Length;
}
throw new InvalidOperationException("Shouldn't happen (VisualLength incorrect?)");
}
/// <summary>
/// Gets the visual top from the specified text line.
/// </summary>
/// <returns>Distance in device-independent pixels
/// from the top of the document to the top of the specified text line.</returns>
public double GetTextLineVisualYPosition(TextLine textLine, VisualYPosition yPositionMode)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
return pos + tl.Baseline - _textView.DefaultBaseline;
case VisualYPosition.TextBottom:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
case VisualYPosition.TextMiddle:
return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
throw new ArgumentException("Invalid yPositionMode:" + yPositionMode);
}
}
pos += tl.Height;
}
throw new ArgumentException("textLine is not a line in this VisualLine");
}
/// <summary>
/// Gets the start visual column from the specified text line.
/// </summary>
public int GetTextLineVisualStartColumn(TextLine textLine)
{
if (!TextLines.Contains(textLine))
throw new ArgumentException("textLine is not a line in this VisualLine");
return TextLines.TakeWhile(tl => tl != textLine).Sum(tl => tl.Length);
}
/// <summary>
/// Gets a TextLine by the visual position.
/// </summary>
public TextLine GetTextLineByVisualYPosition(double visualTop)
{
const double epsilon = 0.0001;
var pos = VisualTop;
foreach (var tl in TextLines)
{
pos += tl.Height;
if (visualTop + epsilon < pos)
return tl;
}
return TextLines[TextLines.Count - 1];
}
/// <summary>
/// Gets the visual position from the specified visualColumn.
/// </summary>
/// <returns>Position in device-independent pixels
/// relative to the top left of the document.</returns>
public Point GetVisualPosition(int visualColumn, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
internal Point GetVisualPosition(int visualColumn, bool isAtEndOfLine, VisualYPosition yPositionMode)
{
var textLine = GetTextLine(visualColumn, isAtEndOfLine);
var xPos = GetTextLineVisualXPosition(textLine, visualColumn);
var yPos = GetTextLineVisualYPosition(textLine, yPositionMode);
return new Point(xPos, yPos);
}
/// <summary>
/// Gets the distance to the left border of the text area of the specified visual column.
/// The visual column must belong to the specified text line.
/// </summary>
public double GetTextLineVisualXPosition(TextLine textLine, int visualColumn)
{
if (textLine == null)
throw new ArgumentNullException(nameof(textLine));
var xPos = textLine.GetDistanceFromCharacterHit(new CharacterHit(Math.Min(visualColumn,
VisualLengthWithEndOfLineMarker)));
if (visualColumn > VisualLengthWithEndOfLineMarker)
{
xPos += (visualColumn - VisualLengthWithEndOfLineMarker) * _textView.WideSpaceWidth;
}
return xPos;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point)
{
return GetVisualColumn(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(Point point, bool allowVirtualSpace)
{
return GetVisualColumn(GetTextLineByVisualYPosition(point.Y), point.X, allowVirtualSpace);
}
internal int GetVisualColumn(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
var vc = GetVisualColumn(textLine, point.X, allowVirtualSpace);
isAtEndOfLine = (vc >= GetTextLineVisualStartColumn(textLine) + textLine.Length);
return vc;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, rounds to the nearest column.
/// </summary>
public int GetVisualColumn(TextLine textLine, double xPos, bool allowVirtualSpace)
{
if (xPos > textLine.WidthIncludingTrailingWhitespace)
{
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
var virtualX = (int)Math.Round((xPos - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth, MidpointRounding.AwayFromZero);
return VisualLengthWithEndOfLineMarker + virtualX;
}
}
var ch = textLine.GetCharacterHitFromDistance(xPos);
return ch.FirstCharacterIndex + ch.TrailingLength;
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(TextViewPosition position, bool allowVirtualSpace)
{
return ValidateVisualColumn(Document.GetOffset(position.Location), position.VisualColumn, allowVirtualSpace);
}
/// <summary>
/// Validates the visual column and returns the correct one.
/// </summary>
public int ValidateVisualColumn(int offset, int visualColumn, bool allowVirtualSpace)
{
var firstDocumentLineOffset = FirstDocumentLine.Offset;
if (visualColumn < 0)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
var offsetFromVisualColumn = GetRelativeOffset(visualColumn);
offsetFromVisualColumn += firstDocumentLineOffset;
if (offsetFromVisualColumn != offset)
{
return GetVisualColumn(offset - firstDocumentLineOffset);
}
if (visualColumn > VisualLength && !allowVirtualSpace)
{
return VisualLength;
}
return visualColumn;
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point)
{
return GetVisualColumnFloor(point, _textView.Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the visual column from a document position (relative to top left of the document).
/// If the user clicks between two visual columns, returns the first of those columns.
/// </summary>
public int GetVisualColumnFloor(Point point, bool allowVirtualSpace)
{
return GetVisualColumnFloor(point, allowVirtualSpace, out _);
}
internal int GetVisualColumnFloor(Point point, bool allowVirtualSpace, out bool isAtEndOfLine)
{
var textLine = GetTextLineByVisualYPosition(point.Y);
if (point.X > textLine.WidthIncludingTrailingWhitespace)
{
isAtEndOfLine = true;
if (allowVirtualSpace && textLine == TextLines[TextLines.Count - 1])
{
// clicking virtual space in the last line
var virtualX = (int)((point.X - textLine.WidthIncludingTrailingWhitespace) / _textView.WideSpaceWidth);
return VisualLengthWithEndOfLineMarker + virtualX;
}
// GetCharacterHitFromDistance returns a hit with FirstCharacterIndex=last character in line
// and TrailingLength=1 when clicking behind the line, so the floor function needs to handle this case
// specially and return the line's end column instead.
return GetTextLineVisualStartColumn(textLine) + textLine.Length;
}
isAtEndOfLine = false;
var ch = textLine.GetCharacterHitFromDistance(point.X);
return ch.FirstCharacterIndex;
}
/// <summary>
/// Gets the text view position from the specified visual column.
/// </summary>
public TextViewPosition GetTextViewPosition(int visualColumn)
{
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
return new TextViewPosition(Document.GetLocation(documentOffset), visualColumn);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPosition(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumn(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <param name="allowVirtualSpace">Controls whether positions in virtual space may be returned.</param>
public TextViewPosition GetTextViewPositionFloor(Point visualPosition, bool allowVirtualSpace)
{
var visualColumn = GetVisualColumnFloor(visualPosition, allowVirtualSpace, out var isAtEndOfLine);
var documentOffset = GetRelativeOffset(visualColumn) + FirstDocumentLine.Offset;
var pos = new TextViewPosition(Document.GetLocation(documentOffset), visualColumn)
{
IsAtEndOfLine = isAtEndOfLine
};
return pos;
}
/// <summary>
/// Gets whether the visual line was disposed.
/// </summary>
public bool IsDisposed => _phase == LifetimePhase.Disposed;
internal void Dispose()
{
if (_phase == LifetimePhase.Disposed)
{
return;
}
Debug.Assert(_phase == LifetimePhase.Live);
_phase = LifetimePhase.Disposed;
if (_visual != null)
{
((ISetLogicalParent)_visual).SetParent(null);
}
}
/// <summary>
/// Gets the next possible caret position after visualColumn, or -1 if there is no caret position.
/// </summary>
public int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode, bool allowVirtualSpace)
{
if (!HasStopsInVirtualSpace(mode))
allowVirtualSpace = false;
if (_elements.Count == 0)
{
// special handling for empty visual lines:
if (allowVirtualSpace)
{
if (direction == LogicalDirection.Forward)
return Math.Max(0, visualColumn + 1);
if (visualColumn > 0)
return visualColumn - 1;
return -1;
}
// even though we don't have any elements,
// there's a single caret stop at visualColumn 0
if (visualColumn < 0 && direction == LogicalDirection.Forward)
return 0;
if (visualColumn > 0 && direction == LogicalDirection.Backward)
return 0;
return -1;
}
int i;
if (direction == LogicalDirection.Backward)
{
// Search Backwards:
// If the last element doesn't handle line borders, return the line end as caret stop
if (visualColumn > VisualLength && !_elements[_elements.Count - 1].HandlesLineBorders && HasImplicitStopAtLineEnd())
{
if (allowVirtualSpace)
return visualColumn - 1;
return VisualLength;
}
// skip elements that start after or at visualColumn
for (i = _elements.Count - 1; i >= 0; i--)
{
if (_elements[i].VisualColumn < visualColumn)
break;
}
// search last element that has a caret stop
for (; i >= 0; i--)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Min(visualColumn, _elements[i].VisualColumn + _elements[i].VisualLength + 1),
direction, mode);
if (pos >= 0)
return pos;
}
// If we've found nothing, and the first element doesn't handle line borders,
// return the line start as normal caret stop.
if (visualColumn > 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
}
else
{
// Search Forwards:
// If the first element doesn't handle line borders, return the line start as caret stop
if (visualColumn < 0 && !_elements[0].HandlesLineBorders && HasImplicitStopAtLineStart(mode))
return 0;
// skip elements that end before or at visualColumn
for (i = 0; i < _elements.Count; i++)
{
if (_elements[i].VisualColumn + _elements[i].VisualLength > visualColumn)
break;
}
// search first element that has a caret stop
for (; i < _elements.Count; i++)
{
var pos = _elements[i].GetNextCaretPosition(
Math.Max(visualColumn, _elements[i].VisualColumn - 1),
direction, mode);
if (pos >= 0)
return pos;
}
// if we've found nothing, and the last element doesn't handle line borders,
// return the line end as caret stop
if ((allowVirtualSpace || !_elements[_elements.Count - 1].HandlesLineBorders) && HasImplicitStopAtLineEnd())
{
if (visualColumn < VisualLength)
return VisualLength;
if (allowVirtualSpace)
return visualColumn + 1;
}
}
// we've found nothing, return -1 and let the caret search continue in the next line
return -1;
}
private static bool HasStopsInVirtualSpace(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineStart(CaretPositioningMode mode)
{
return mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint;
}
private static bool HasImplicitStopAtLineEnd() => true;
private VisualLineDrawingVisual _visual;
internal VisualLineDrawingVisual Render()
{
Debug.Assert(_phase == LifetimePhase.Live);
if (_visual == null)
{
_visual = new VisualLineDrawingVisual(this);
((ISetLogicalParent)_visual).SetParent(_textView);
}
return _visual;
}
}
// TODO: can inherit from Layoutable, but dev tools crash
internal sealed class VisualLineDrawingVisual : Control
{
public VisualLine VisualLine { get; }
public double LineHeight { get; }
internal bool IsAdded { get; set; }
public VisualLineDrawingVisual(VisualLine visualLine)
{
VisualLine = visualLine;
LineHeight = VisualLine.TextLines.Sum(textLine => textLine.Height);
}
public override void Render(DrawingContext context)
{
double pos = 0;
foreach (var textLine in VisualLine.TextLines)
{
textLine.Draw(context, new Point(0, pos));
pos += textLine.Height;
}
}
}
}
<MSG> render caret the correct size and at correct location.
<DFF> @@ -375,11 +375,11 @@ namespace AvaloniaEdit.Rendering
case VisualYPosition.LineBottom:
return pos + tl.Height;
case VisualYPosition.TextTop:
- return pos + tl.Baseline - _textView.DefaultBaseline;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor);
case VisualYPosition.TextBottom:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor);
case VisualYPosition.TextMiddle:
- return pos + tl.Baseline - _textView.DefaultBaseline + _textView.DefaultLineHeight / 2;
+ return pos + tl.Baseline - (_textView.DefaultBaseline * TextLineRun.BaselineFactor) + (_textView.DefaultLineHeight * TextLineRun.HeightFactor) / 2;
case VisualYPosition.Baseline:
return pos + tl.Baseline;
default:
| 3 | render caret the correct size and at correct location. | 3 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057910 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057911 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057912 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057913 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057914 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057915 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057916 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057917 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057918 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057919 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057920 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057921 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057922 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057923 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057924 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
Background="Gray"
Margin="30"
Foreground="White"
SyntaxHighlighting="XML"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
TextBlock.FontSize="30" />
</DockPanel>
</Window>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> update editor.
<DFF> @@ -16,12 +16,15 @@
<Button Name="clearControlBtn" Content="Clear Buttons" />
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
+ FontFamily="Cascadia Code"
Background="Gray"
Margin="30"
Foreground="White"
- SyntaxHighlighting="XML"
+ SyntaxHighlighting="C#"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
- TextBlock.FontSize="30" />
+ FontWeight="Light"
+
+ FontSize="18" />
</DockPanel>
</Window>
\ No newline at end of file
| 5 | update editor. | 2 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10057925 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057926 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057927 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057928 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057929 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057930 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057931 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057932 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057933 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057934 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057935 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057936 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057937 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057938 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057939 | <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);
_mode = SelectionMode.None;
if (!e.Handled)
{
var modifiers = e.KeyModifiers;
var shift = modifiers.HasFlag(KeyModifiers.Shift);
if (_enableTextDragDrop && e.ClickCount == 1 && !shift)
{
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;
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
{
_mode = SelectionMode.Normal;
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> fix selection mode.
<DFF> @@ -431,6 +431,14 @@ namespace AvaloniaEdit.Editing
}
}
else if (e.ClickCount == 1 && modifiers.HasFlag(InputModifiers.Control))
+ {
+ _mode = SelectionMode.WholeWord;
+ if (shift && !(TextArea.Selection is RectangleSelection))
+ {
+ TextArea.Selection = TextArea.Selection.StartSelectionOrSetEndpoint(oldPosition, TextArea.Caret.Position);
+ }
+ }
+ else if(e.ClickCount == 1 && modifiers == InputModifiers.LeftMouseButton)
{
_mode = SelectionMode.Normal;
if (shift && !(TextArea.Selection is RectangleSelection))
| 8 | fix selection mode. | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057940 | <NME> jsgrid.css
<BEF> .jsgrid {
position: relative;
overflow: hidden;
font-size: 1em;
}
.jsgrid, .jsgrid *, .jsgrid *:before, .jsgrid *:after {
box-sizing: border-box;
}
.jsgrid input,
.jsgrid textarea,
.jsgrid select {
font-size: 1em;
}
.jsgrid-grid-header {
overflow-x: hidden;
overflow-y: scroll;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
.jsgrid-grid-body {
overflow-x: auto;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
.jsgrid-table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
border-spacing: 0;
}
.jsgrid-cell {
padding: 0.5em 0.5em;
}
.jsgrid-cell,
.jsgrid-header-cell {
box-sizing: border-box;
}
.jsgrid-align-left {
text-align: left;
}
.jsgrid-align-center,
.jsgrid-align-center input,
.jsgrid-align-center textarea,
.jsgrid-align-center select {
text-align: center;
}
.jsgrid-align-right,
.jsgrid-align-right input,
.jsgrid-align-right textarea,
.jsgrid-align-right select {
text-align: right;
}
.jsgrid-header-cell {
padding: .5em .5em;
}
.jsgrid-filter-row input,
.jsgrid-filter-row textarea,
.jsgrid-filter-row select,
.jsgrid-edit-row input,
.jsgrid-edit-row textarea,
.jsgrid-edit-row select,
.jsgrid-insert-row input,
.jsgrid-insert-row textarea,
.jsgrid-insert-row select {
width: 100%;
padding: .3em .5em;
}
.jsgrid-filter-row input[type='checkbox'],
.jsgrid-edit-row input[type='checkbox'],
.jsgrid-insert-row input[type='checkbox'] {
width: auto;
}
.jsgrid-selected-row .jsgrid-cell {
cursor: pointer;
}
.jsgrid-nodata-row .jsgrid-cell {
padding: .5em 0;
text-align: center;
}
.jsgrid-header-sort {
cursor: pointer;
}
.jsgrid-pager {
padding-top: .5em;
}
.jsgrid-pager-nav-button {
padding: .2em .6em;
}
.jsgrid-pager-nav-inactive-button {
display: none;
pointer-events: none;
}
.jsgrid-pager-page {
padding: .2em .6em;
}
<MSG> Theme: Pager bottom padding
<DFF> @@ -103,7 +103,7 @@
}
.jsgrid-pager {
- padding-top: .5em;
+ padding: .5em 0;
}
.jsgrid-pager-nav-button {
| 1 | Theme: Pager bottom padding | 1 | .css | css | mit | tabalinas/jsgrid |
10057941 | <NME> jsgrid.css
<BEF> .jsgrid {
position: relative;
overflow: hidden;
font-size: 1em;
}
.jsgrid, .jsgrid *, .jsgrid *:before, .jsgrid *:after {
box-sizing: border-box;
}
.jsgrid input,
.jsgrid textarea,
.jsgrid select {
font-size: 1em;
}
.jsgrid-grid-header {
overflow-x: hidden;
overflow-y: scroll;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
.jsgrid-grid-body {
overflow-x: auto;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
.jsgrid-table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
border-spacing: 0;
}
.jsgrid-cell {
padding: 0.5em 0.5em;
}
.jsgrid-cell,
.jsgrid-header-cell {
box-sizing: border-box;
}
.jsgrid-align-left {
text-align: left;
}
.jsgrid-align-center,
.jsgrid-align-center input,
.jsgrid-align-center textarea,
.jsgrid-align-center select {
text-align: center;
}
.jsgrid-align-right,
.jsgrid-align-right input,
.jsgrid-align-right textarea,
.jsgrid-align-right select {
text-align: right;
}
.jsgrid-header-cell {
padding: .5em .5em;
}
.jsgrid-filter-row input,
.jsgrid-filter-row textarea,
.jsgrid-filter-row select,
.jsgrid-edit-row input,
.jsgrid-edit-row textarea,
.jsgrid-edit-row select,
.jsgrid-insert-row input,
.jsgrid-insert-row textarea,
.jsgrid-insert-row select {
width: 100%;
padding: .3em .5em;
}
.jsgrid-filter-row input[type='checkbox'],
.jsgrid-edit-row input[type='checkbox'],
.jsgrid-insert-row input[type='checkbox'] {
width: auto;
}
.jsgrid-selected-row .jsgrid-cell {
cursor: pointer;
}
.jsgrid-nodata-row .jsgrid-cell {
padding: .5em 0;
text-align: center;
}
.jsgrid-header-sort {
cursor: pointer;
}
.jsgrid-pager {
padding-top: .5em;
}
.jsgrid-pager-nav-button {
padding: .2em .6em;
}
.jsgrid-pager-nav-inactive-button {
display: none;
pointer-events: none;
}
.jsgrid-pager-page {
padding: .2em .6em;
}
<MSG> Theme: Pager bottom padding
<DFF> @@ -103,7 +103,7 @@
}
.jsgrid-pager {
- padding-top: .5em;
+ padding: .5em 0;
}
.jsgrid-pager-nav-button {
| 1 | Theme: Pager bottom padding | 1 | .css | css | mit | tabalinas/jsgrid |
10057942 | <NME> OverloadInsightWindow.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 AvaloniaEdit.Editing;
using Avalonia.Input;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// Insight window that shows an OverloadViewer.
/// </summary>
public class OverloadInsightWindow : InsightWindow
{
private readonly OverloadViewer _overloadViewer = new OverloadViewer();
/// <summary>
/// Creates a new OverloadInsightWindow.
/// </summary>
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
Content = _overloadViewer;
}
/// <summary>
/// Gets/Sets the item provider.
/// </summary>
public IOverloadProvider Provider
{
get => _overloadViewer.Provider;
set => _overloadViewer.Provider = value;
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && Provider != null && Provider.Count > 1)
{
switch (e.Key)
{
case Key.Up:
e.Handled = true;
_overloadViewer.ChangeIndex(-1);
break;
case Key.Down:
e.Handled = true;
_overloadViewer.ChangeIndex(+1);
break;
}
if (e.Handled)
{
// TODO: UpdateLayout();
UpdatePosition();
}
}
}
}
}
<MSG> Merge pull request #91 from HendrikMennen/RemovePopupRoot
Update Avalonia + Use Popup instead of PopupRoot
<DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
- Content = _overloadViewer;
+ Child = _overloadViewer;
}
/// <summary>
| 1 | Merge pull request #91 from HendrikMennen/RemovePopupRoot | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057943 | <NME> OverloadInsightWindow.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 AvaloniaEdit.Editing;
using Avalonia.Input;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// Insight window that shows an OverloadViewer.
/// </summary>
public class OverloadInsightWindow : InsightWindow
{
private readonly OverloadViewer _overloadViewer = new OverloadViewer();
/// <summary>
/// Creates a new OverloadInsightWindow.
/// </summary>
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
Content = _overloadViewer;
}
/// <summary>
/// Gets/Sets the item provider.
/// </summary>
public IOverloadProvider Provider
{
get => _overloadViewer.Provider;
set => _overloadViewer.Provider = value;
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && Provider != null && Provider.Count > 1)
{
switch (e.Key)
{
case Key.Up:
e.Handled = true;
_overloadViewer.ChangeIndex(-1);
break;
case Key.Down:
e.Handled = true;
_overloadViewer.ChangeIndex(+1);
break;
}
if (e.Handled)
{
// TODO: UpdateLayout();
UpdatePosition();
}
}
}
}
}
<MSG> Merge pull request #91 from HendrikMennen/RemovePopupRoot
Update Avalonia + Use Popup instead of PopupRoot
<DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
- Content = _overloadViewer;
+ Child = _overloadViewer;
}
/// <summary>
| 1 | Merge pull request #91 from HendrikMennen/RemovePopupRoot | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057944 | <NME> OverloadInsightWindow.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 AvaloniaEdit.Editing;
using Avalonia.Input;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// Insight window that shows an OverloadViewer.
/// </summary>
public class OverloadInsightWindow : InsightWindow
{
private readonly OverloadViewer _overloadViewer = new OverloadViewer();
/// <summary>
/// Creates a new OverloadInsightWindow.
/// </summary>
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
Content = _overloadViewer;
}
/// <summary>
/// Gets/Sets the item provider.
/// </summary>
public IOverloadProvider Provider
{
get => _overloadViewer.Provider;
set => _overloadViewer.Provider = value;
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && Provider != null && Provider.Count > 1)
{
switch (e.Key)
{
case Key.Up:
e.Handled = true;
_overloadViewer.ChangeIndex(-1);
break;
case Key.Down:
e.Handled = true;
_overloadViewer.ChangeIndex(+1);
break;
}
if (e.Handled)
{
// TODO: UpdateLayout();
UpdatePosition();
}
}
}
}
}
<MSG> Merge pull request #91 from HendrikMennen/RemovePopupRoot
Update Avalonia + Use Popup instead of PopupRoot
<DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
- Content = _overloadViewer;
+ Child = _overloadViewer;
}
/// <summary>
| 1 | Merge pull request #91 from HendrikMennen/RemovePopupRoot | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057945 | <NME> OverloadInsightWindow.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 AvaloniaEdit.Editing;
using Avalonia.Input;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// Insight window that shows an OverloadViewer.
/// </summary>
public class OverloadInsightWindow : InsightWindow
{
private readonly OverloadViewer _overloadViewer = new OverloadViewer();
/// <summary>
/// Creates a new OverloadInsightWindow.
/// </summary>
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
Content = _overloadViewer;
}
/// <summary>
/// Gets/Sets the item provider.
/// </summary>
public IOverloadProvider Provider
{
get => _overloadViewer.Provider;
set => _overloadViewer.Provider = value;
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && Provider != null && Provider.Count > 1)
{
switch (e.Key)
{
case Key.Up:
e.Handled = true;
_overloadViewer.ChangeIndex(-1);
break;
case Key.Down:
e.Handled = true;
_overloadViewer.ChangeIndex(+1);
break;
}
if (e.Handled)
{
// TODO: UpdateLayout();
UpdatePosition();
}
}
}
}
}
<MSG> Merge pull request #91 from HendrikMennen/RemovePopupRoot
Update Avalonia + Use Popup instead of PopupRoot
<DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
- Content = _overloadViewer;
+ Child = _overloadViewer;
}
/// <summary>
| 1 | Merge pull request #91 from HendrikMennen/RemovePopupRoot | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057946 | <NME> OverloadInsightWindow.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 AvaloniaEdit.Editing;
using Avalonia.Input;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// Insight window that shows an OverloadViewer.
/// </summary>
public class OverloadInsightWindow : InsightWindow
{
private readonly OverloadViewer _overloadViewer = new OverloadViewer();
/// <summary>
/// Creates a new OverloadInsightWindow.
/// </summary>
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
Content = _overloadViewer;
}
/// <summary>
/// Gets/Sets the item provider.
/// </summary>
public IOverloadProvider Provider
{
get => _overloadViewer.Provider;
set => _overloadViewer.Provider = value;
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && Provider != null && Provider.Count > 1)
{
switch (e.Key)
{
case Key.Up:
e.Handled = true;
_overloadViewer.ChangeIndex(-1);
break;
case Key.Down:
e.Handled = true;
_overloadViewer.ChangeIndex(+1);
break;
}
if (e.Handled)
{
// TODO: UpdateLayout();
UpdatePosition();
}
}
}
}
}
<MSG> Merge pull request #91 from HendrikMennen/RemovePopupRoot
Update Avalonia + Use Popup instead of PopupRoot
<DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
- Content = _overloadViewer;
+ Child = _overloadViewer;
}
/// <summary>
| 1 | Merge pull request #91 from HendrikMennen/RemovePopupRoot | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057947 | <NME> OverloadInsightWindow.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 AvaloniaEdit.Editing;
using Avalonia.Input;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// Insight window that shows an OverloadViewer.
/// </summary>
public class OverloadInsightWindow : InsightWindow
{
private readonly OverloadViewer _overloadViewer = new OverloadViewer();
/// <summary>
/// Creates a new OverloadInsightWindow.
/// </summary>
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
Content = _overloadViewer;
}
/// <summary>
/// Gets/Sets the item provider.
/// </summary>
public IOverloadProvider Provider
{
get => _overloadViewer.Provider;
set => _overloadViewer.Provider = value;
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && Provider != null && Provider.Count > 1)
{
switch (e.Key)
{
case Key.Up:
e.Handled = true;
_overloadViewer.ChangeIndex(-1);
break;
case Key.Down:
e.Handled = true;
_overloadViewer.ChangeIndex(+1);
break;
}
if (e.Handled)
{
// TODO: UpdateLayout();
UpdatePosition();
}
}
}
}
}
<MSG> Merge pull request #91 from HendrikMennen/RemovePopupRoot
Update Avalonia + Use Popup instead of PopupRoot
<DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
- Content = _overloadViewer;
+ Child = _overloadViewer;
}
/// <summary>
| 1 | Merge pull request #91 from HendrikMennen/RemovePopupRoot | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057948 | <NME> OverloadInsightWindow.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 AvaloniaEdit.Editing;
using Avalonia.Input;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// Insight window that shows an OverloadViewer.
/// </summary>
public class OverloadInsightWindow : InsightWindow
{
private readonly OverloadViewer _overloadViewer = new OverloadViewer();
/// <summary>
/// Creates a new OverloadInsightWindow.
/// </summary>
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
Content = _overloadViewer;
}
/// <summary>
/// Gets/Sets the item provider.
/// </summary>
public IOverloadProvider Provider
{
get => _overloadViewer.Provider;
set => _overloadViewer.Provider = value;
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && Provider != null && Provider.Count > 1)
{
switch (e.Key)
{
case Key.Up:
e.Handled = true;
_overloadViewer.ChangeIndex(-1);
break;
case Key.Down:
e.Handled = true;
_overloadViewer.ChangeIndex(+1);
break;
}
if (e.Handled)
{
// TODO: UpdateLayout();
UpdatePosition();
}
}
}
}
}
<MSG> Merge pull request #91 from HendrikMennen/RemovePopupRoot
Update Avalonia + Use Popup instead of PopupRoot
<DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
- Content = _overloadViewer;
+ Child = _overloadViewer;
}
/// <summary>
| 1 | Merge pull request #91 from HendrikMennen/RemovePopupRoot | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10057949 | <NME> OverloadInsightWindow.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 AvaloniaEdit.Editing;
using Avalonia.Input;
namespace AvaloniaEdit.CodeCompletion
{
/// <summary>
/// Insight window that shows an OverloadViewer.
/// </summary>
public class OverloadInsightWindow : InsightWindow
{
private readonly OverloadViewer _overloadViewer = new OverloadViewer();
/// <summary>
/// Creates a new OverloadInsightWindow.
/// </summary>
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
Content = _overloadViewer;
}
/// <summary>
/// Gets/Sets the item provider.
/// </summary>
public IOverloadProvider Provider
{
get => _overloadViewer.Provider;
set => _overloadViewer.Provider = value;
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && Provider != null && Provider.Count > 1)
{
switch (e.Key)
{
case Key.Up:
e.Handled = true;
_overloadViewer.ChangeIndex(-1);
break;
case Key.Down:
e.Handled = true;
_overloadViewer.ChangeIndex(+1);
break;
}
if (e.Handled)
{
// TODO: UpdateLayout();
UpdatePosition();
}
}
}
}
}
<MSG> Merge pull request #91 from HendrikMennen/RemovePopupRoot
Update Avalonia + Use Popup instead of PopupRoot
<DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion
public OverloadInsightWindow(TextArea textArea) : base(textArea)
{
_overloadViewer.Margin = new Thickness(2, 0, 0, 0);
- Content = _overloadViewer;
+ Child = _overloadViewer;
}
/// <summary>
| 1 | Merge pull request #91 from HendrikMennen/RemovePopupRoot | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.