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
10062850
<NME> LineNumberMargin.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; namespace AvaloniaEdit.Editing { /// <summary> /// Margin showing line numbers. /// </summary> public class LineNumberMargin : AbstractMargin { private AnchorSegment _selectionStart; private bool _selecting; /// <summary> /// The typeface used for rendering the line number margin. /// This field is calculated in MeasureOverride() based on the FontFamily etc. properties. /// </summary> protected Typeface Typeface { get; set; } /// <summary> /// The font size used for rendering the line number margin. /// This field is calculated in MeasureOverride() based on the FontFamily etc. properties. /// </summary> protected double EmSize { get; set; } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { Typeface = this.CreateTypeface(); EmSize = GetValue(TextBlock.FontSizeProperty); var text = TextFormatterFactory.CreateFormattedText( this, new string('9', MaxLineNumberLength), Typeface, EmSize, GetValue(TextBlock.ForegroundProperty) ); return new Size(text.Width, 0); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { EmSize = GetValue(TextBlock.FontSizeProperty); var textView = TextView; var renderSize = Bounds.Size; if (textView != null && textView.VisualLinesValid) { var foreground = GetValue(TemplatedControl.ForegroundProperty); foreach (var line in textView.VisualLines) { this, lineNumber.ToString(CultureInfo.CurrentCulture), Typeface, EmSize, foreground ); var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop); drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset)); } } } /// <inheritdoc/> protected override void OnTextViewChanged(TextView oldTextView, TextView newTextView) { if (oldTextView != null) { oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged; } base.OnTextViewChanged(oldTextView, newTextView); if (newTextView != null) { newTextView.VisualLinesChanged += TextViewVisualLinesChanged; } InvalidateVisual(); } /// <inheritdoc/> protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument) { if (oldDocument != null) { TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged); } base.OnDocumentChanged(oldDocument, newDocument); if (newDocument != null) { TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged); } OnDocumentLineCountChanged(); } private void OnDocumentLineCountChanged(object sender, EventArgs e) { OnDocumentLineCountChanged(); } void TextViewVisualLinesChanged(object sender, EventArgs e) { InvalidateMeasure(); } /// <summary> /// Maximum length of a line number, in characters /// </summary> protected int MaxLineNumberLength = 1; private void OnDocumentLineCountChanged() { var documentLineCount = Document?.LineCount ?? 1; var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length; // The margin looks too small when there is only one digit, so always reserve space for // at least two digits if (newLength < 2) newLength = 2; if (newLength != MaxLineNumberLength) { MaxLineNumberLength = newLength; InvalidateMeasure(); } } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled && TextView != null && TextArea != null) { e.Handled = true; TextArea.Focus(); var currentSeg = GetTextLineSegment(e); if (currentSeg == SimpleSegment.Invalid) return; TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length; e.Pointer.Capture(this); if (e.Pointer.Captured == this) { _selecting = true; _selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length); if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { if (TextArea.Selection is SimpleSelection simpleSelection) _selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment); } TextArea.Selection = Selection.Create(TextArea, _selectionStart); if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { ExtendSelection(currentSeg); } TextArea.Caret.BringCaretToView(0); } } } private SimpleSegment GetTextLineSegment(PointerEventArgs e) { var pos = e.GetPosition(TextView); pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset); var vl = TextView.GetVisualLineFromVisualTop(pos.Y); if (vl == null) return SimpleSegment.Invalid; var tl = vl.GetTextLineByVisualYPosition(pos.Y); var visualStartColumn = vl.GetTextLineVisualStartColumn(tl); var visualEndColumn = visualStartColumn + tl.Length; var relStart = vl.FirstDocumentLine.Offset; var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart; var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart; if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length) endOffset += vl.LastDocumentLine.DelimiterLength; return new SimpleSegment(startOffset, endOffset - startOffset); } private void ExtendSelection(SimpleSegment currentSeg) { if (currentSeg.Offset < _selectionStart.Offset) { TextArea.Caret.Offset = currentSeg.Offset; TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length); } else { TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length; TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length); } } protected override void OnPointerMoved(PointerEventArgs e) { if (_selecting && TextArea != null && TextView != null) { e.Handled = true; var currentSeg = GetTextLineSegment(e); if (currentSeg == SimpleSegment.Invalid) return; ExtendSelection(currentSeg); TextArea.Caret.BringCaretToView(0); } base.OnPointerMoved(e); } protected override void OnPointerReleased(PointerReleasedEventArgs e) { if (_selecting) { _selecting = false; _selectionStart = null; e.Pointer.Capture(null); e.Handled = true; } base.OnPointerReleased(e); } } } <MSG> move into if <DFF> @@ -68,12 +68,11 @@ namespace AvaloniaEdit.Editing /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - EmSize = GetValue(TextBlock.FontSizeProperty); - var textView = TextView; var renderSize = Bounds.Size; if (textView != null && textView.VisualLinesValid) { + EmSize = GetValue(TextBlock.FontSizeProperty); var foreground = GetValue(TemplatedControl.ForegroundProperty); foreach (var line in textView.VisualLines) {
1
move into if
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062851
<NME> LineNumberMargin.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; namespace AvaloniaEdit.Editing { /// <summary> /// Margin showing line numbers. /// </summary> public class LineNumberMargin : AbstractMargin { private AnchorSegment _selectionStart; private bool _selecting; /// <summary> /// The typeface used for rendering the line number margin. /// This field is calculated in MeasureOverride() based on the FontFamily etc. properties. /// </summary> protected Typeface Typeface { get; set; } /// <summary> /// The font size used for rendering the line number margin. /// This field is calculated in MeasureOverride() based on the FontFamily etc. properties. /// </summary> protected double EmSize { get; set; } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { Typeface = this.CreateTypeface(); EmSize = GetValue(TextBlock.FontSizeProperty); var text = TextFormatterFactory.CreateFormattedText( this, new string('9', MaxLineNumberLength), Typeface, EmSize, GetValue(TextBlock.ForegroundProperty) ); return new Size(text.Width, 0); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { EmSize = GetValue(TextBlock.FontSizeProperty); var textView = TextView; var renderSize = Bounds.Size; if (textView != null && textView.VisualLinesValid) { var foreground = GetValue(TemplatedControl.ForegroundProperty); foreach (var line in textView.VisualLines) { this, lineNumber.ToString(CultureInfo.CurrentCulture), Typeface, EmSize, foreground ); var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop); drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset)); } } } /// <inheritdoc/> protected override void OnTextViewChanged(TextView oldTextView, TextView newTextView) { if (oldTextView != null) { oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged; } base.OnTextViewChanged(oldTextView, newTextView); if (newTextView != null) { newTextView.VisualLinesChanged += TextViewVisualLinesChanged; } InvalidateVisual(); } /// <inheritdoc/> protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument) { if (oldDocument != null) { TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged); } base.OnDocumentChanged(oldDocument, newDocument); if (newDocument != null) { TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged); } OnDocumentLineCountChanged(); } private void OnDocumentLineCountChanged(object sender, EventArgs e) { OnDocumentLineCountChanged(); } void TextViewVisualLinesChanged(object sender, EventArgs e) { InvalidateMeasure(); } /// <summary> /// Maximum length of a line number, in characters /// </summary> protected int MaxLineNumberLength = 1; private void OnDocumentLineCountChanged() { var documentLineCount = Document?.LineCount ?? 1; var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length; // The margin looks too small when there is only one digit, so always reserve space for // at least two digits if (newLength < 2) newLength = 2; if (newLength != MaxLineNumberLength) { MaxLineNumberLength = newLength; InvalidateMeasure(); } } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled && TextView != null && TextArea != null) { e.Handled = true; TextArea.Focus(); var currentSeg = GetTextLineSegment(e); if (currentSeg == SimpleSegment.Invalid) return; TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length; e.Pointer.Capture(this); if (e.Pointer.Captured == this) { _selecting = true; _selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length); if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { if (TextArea.Selection is SimpleSelection simpleSelection) _selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment); } TextArea.Selection = Selection.Create(TextArea, _selectionStart); if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { ExtendSelection(currentSeg); } TextArea.Caret.BringCaretToView(0); } } } private SimpleSegment GetTextLineSegment(PointerEventArgs e) { var pos = e.GetPosition(TextView); pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset); var vl = TextView.GetVisualLineFromVisualTop(pos.Y); if (vl == null) return SimpleSegment.Invalid; var tl = vl.GetTextLineByVisualYPosition(pos.Y); var visualStartColumn = vl.GetTextLineVisualStartColumn(tl); var visualEndColumn = visualStartColumn + tl.Length; var relStart = vl.FirstDocumentLine.Offset; var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart; var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart; if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length) endOffset += vl.LastDocumentLine.DelimiterLength; return new SimpleSegment(startOffset, endOffset - startOffset); } private void ExtendSelection(SimpleSegment currentSeg) { if (currentSeg.Offset < _selectionStart.Offset) { TextArea.Caret.Offset = currentSeg.Offset; TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length); } else { TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length; TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length); } } protected override void OnPointerMoved(PointerEventArgs e) { if (_selecting && TextArea != null && TextView != null) { e.Handled = true; var currentSeg = GetTextLineSegment(e); if (currentSeg == SimpleSegment.Invalid) return; ExtendSelection(currentSeg); TextArea.Caret.BringCaretToView(0); } base.OnPointerMoved(e); } protected override void OnPointerReleased(PointerReleasedEventArgs e) { if (_selecting) { _selecting = false; _selectionStart = null; e.Pointer.Capture(null); e.Handled = true; } base.OnPointerReleased(e); } } } <MSG> move into if <DFF> @@ -68,12 +68,11 @@ namespace AvaloniaEdit.Editing /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - EmSize = GetValue(TextBlock.FontSizeProperty); - var textView = TextView; var renderSize = Bounds.Size; if (textView != null && textView.VisualLinesValid) { + EmSize = GetValue(TextBlock.FontSizeProperty); var foreground = GetValue(TemplatedControl.ForegroundProperty); foreach (var line in textView.VisualLines) {
1
move into if
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062852
<NME> LineNumberMargin.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Media; namespace AvaloniaEdit.Editing { /// <summary> /// Margin showing line numbers. /// </summary> public class LineNumberMargin : AbstractMargin { private AnchorSegment _selectionStart; private bool _selecting; /// <summary> /// The typeface used for rendering the line number margin. /// This field is calculated in MeasureOverride() based on the FontFamily etc. properties. /// </summary> protected Typeface Typeface { get; set; } /// <summary> /// The font size used for rendering the line number margin. /// This field is calculated in MeasureOverride() based on the FontFamily etc. properties. /// </summary> protected double EmSize { get; set; } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { Typeface = this.CreateTypeface(); EmSize = GetValue(TextBlock.FontSizeProperty); var text = TextFormatterFactory.CreateFormattedText( this, new string('9', MaxLineNumberLength), Typeface, EmSize, GetValue(TextBlock.ForegroundProperty) ); return new Size(text.Width, 0); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { EmSize = GetValue(TextBlock.FontSizeProperty); var textView = TextView; var renderSize = Bounds.Size; if (textView != null && textView.VisualLinesValid) { var foreground = GetValue(TemplatedControl.ForegroundProperty); foreach (var line in textView.VisualLines) { this, lineNumber.ToString(CultureInfo.CurrentCulture), Typeface, EmSize, foreground ); var y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop); drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset)); } } } /// <inheritdoc/> protected override void OnTextViewChanged(TextView oldTextView, TextView newTextView) { if (oldTextView != null) { oldTextView.VisualLinesChanged -= TextViewVisualLinesChanged; } base.OnTextViewChanged(oldTextView, newTextView); if (newTextView != null) { newTextView.VisualLinesChanged += TextViewVisualLinesChanged; } InvalidateVisual(); } /// <inheritdoc/> protected override void OnDocumentChanged(TextDocument oldDocument, TextDocument newDocument) { if (oldDocument != null) { TextDocumentWeakEventManager.LineCountChanged.RemoveHandler(oldDocument, OnDocumentLineCountChanged); } base.OnDocumentChanged(oldDocument, newDocument); if (newDocument != null) { TextDocumentWeakEventManager.LineCountChanged.AddHandler(newDocument, OnDocumentLineCountChanged); } OnDocumentLineCountChanged(); } private void OnDocumentLineCountChanged(object sender, EventArgs e) { OnDocumentLineCountChanged(); } void TextViewVisualLinesChanged(object sender, EventArgs e) { InvalidateMeasure(); } /// <summary> /// Maximum length of a line number, in characters /// </summary> protected int MaxLineNumberLength = 1; private void OnDocumentLineCountChanged() { var documentLineCount = Document?.LineCount ?? 1; var newLength = documentLineCount.ToString(CultureInfo.CurrentCulture).Length; // The margin looks too small when there is only one digit, so always reserve space for // at least two digits if (newLength < 2) newLength = 2; if (newLength != MaxLineNumberLength) { MaxLineNumberLength = newLength; InvalidateMeasure(); } } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled && TextView != null && TextArea != null) { e.Handled = true; TextArea.Focus(); var currentSeg = GetTextLineSegment(e); if (currentSeg == SimpleSegment.Invalid) return; TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length; e.Pointer.Capture(this); if (e.Pointer.Captured == this) { _selecting = true; _selectionStart = new AnchorSegment(Document, currentSeg.Offset, currentSeg.Length); if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { if (TextArea.Selection is SimpleSelection simpleSelection) _selectionStart = new AnchorSegment(Document, simpleSelection.SurroundingSegment); } TextArea.Selection = Selection.Create(TextArea, _selectionStart); if (e.KeyModifiers.HasFlag(KeyModifiers.Shift)) { ExtendSelection(currentSeg); } TextArea.Caret.BringCaretToView(0); } } } private SimpleSegment GetTextLineSegment(PointerEventArgs e) { var pos = e.GetPosition(TextView); pos = new Point(0, pos.Y.CoerceValue(0, TextView.Bounds.Height) + TextView.VerticalOffset); var vl = TextView.GetVisualLineFromVisualTop(pos.Y); if (vl == null) return SimpleSegment.Invalid; var tl = vl.GetTextLineByVisualYPosition(pos.Y); var visualStartColumn = vl.GetTextLineVisualStartColumn(tl); var visualEndColumn = visualStartColumn + tl.Length; var relStart = vl.FirstDocumentLine.Offset; var startOffset = vl.GetRelativeOffset(visualStartColumn) + relStart; var endOffset = vl.GetRelativeOffset(visualEndColumn) + relStart; if (endOffset == vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length) endOffset += vl.LastDocumentLine.DelimiterLength; return new SimpleSegment(startOffset, endOffset - startOffset); } private void ExtendSelection(SimpleSegment currentSeg) { if (currentSeg.Offset < _selectionStart.Offset) { TextArea.Caret.Offset = currentSeg.Offset; TextArea.Selection = Selection.Create(TextArea, currentSeg.Offset, _selectionStart.Offset + _selectionStart.Length); } else { TextArea.Caret.Offset = currentSeg.Offset + currentSeg.Length; TextArea.Selection = Selection.Create(TextArea, _selectionStart.Offset, currentSeg.Offset + currentSeg.Length); } } protected override void OnPointerMoved(PointerEventArgs e) { if (_selecting && TextArea != null && TextView != null) { e.Handled = true; var currentSeg = GetTextLineSegment(e); if (currentSeg == SimpleSegment.Invalid) return; ExtendSelection(currentSeg); TextArea.Caret.BringCaretToView(0); } base.OnPointerMoved(e); } protected override void OnPointerReleased(PointerReleasedEventArgs e) { if (_selecting) { _selecting = false; _selectionStart = null; e.Pointer.Capture(null); e.Handled = true; } base.OnPointerReleased(e); } } } <MSG> move into if <DFF> @@ -68,12 +68,11 @@ namespace AvaloniaEdit.Editing /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - EmSize = GetValue(TextBlock.FontSizeProperty); - var textView = TextView; var renderSize = Bounds.Size; if (textView != null && textView.VisualLinesValid) { + EmSize = GetValue(TextBlock.FontSizeProperty); var foreground = GetValue(TemplatedControl.ForegroundProperty); foreach (var line in textView.VisualLines) {
1
move into if
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062853
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062854
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062855
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062856
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062857
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062858
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062859
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062860
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062861
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062862
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062863
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062864
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062865
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062866
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062867
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } Language language = (Language)_syntaxModeCombo.SelectedItem; Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), } } class CustomFormatTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Extract a method and chose a more verbose name for the transformer <DFF> @@ -92,7 +92,7 @@ namespace AvaloniaEdit.Demo "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); - _textEditor.TextArea.TextView.LineTransformers.Add(new CustomFormatTransformer()); + _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); @@ -120,13 +120,7 @@ namespace AvaloniaEdit.Demo private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { - for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) - { - if (_textEditor.TextArea.TextView.LineTransformers[i] is CustomFormatTransformer) - { - _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); - } - } + RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -152,6 +146,17 @@ namespace AvaloniaEdit.Demo } } + private void RemoveUnderlineAndStrikethroughTransformer() + { + for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) + { + if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) + { + _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); + } + } + } + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -238,7 +243,7 @@ namespace AvaloniaEdit.Demo } } - class CustomFormatTransformer : DocumentColorizingTransformer + class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) {
14
Extract a method and chose a more verbose name for the transformer
9
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062868
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); moduleIdAttr: 'data-module-id', moduleTypeAttr: 'data-module-type', moduleDataAttr: 'data-model-data', moduleParentAttr: 'data-parent', mustacheSlotArrayName: 'children', templates: undefined, debug: 0 fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; escape: window.escape, unescape: window.unescape, extend: function(original) { // Loop over every argument after the first. slice.call(arguments, 1).forEach(function(source) { return child; }, insertChild: function(child, parent, index) { if (!parent) return; if (typeof index !== 'undefined') { } }, insert: function(item, array, index) { if (typeof index !== 'undefined') { array.splice(index, 0, item); }, /** * Replaces the contents of the one node with contents * of another. * * http://jsperf.com/replacing-element-vs-replacing-contents/3 * * @param {Element} replacement * @param {Element} current * @return {Element} */ replaceContent: function(replacement, current) { current.innerHTML = ''; var children = replacement.childNodes; for (var i = 0, l = children.length; i < l; i++) { current.appendChild(children[0]); } return current; }, toNode: function(string) { if (typeof string !== 'string') return string; var el = document.createElement('div'); return el.firstElementChild; }, uniqueId: (function() { var counter = 1; return function(prefix) { } }; /** * VIEW */ * @constructor * @param {Object} options */ var DefaultView = function(options) { var domChildren, i, l; this._configure(options); // Save a reference to this model in the globals. this._globals.id[this._id] = this; // Don't look for module nodes in the // view element if we have flagged not to. // When we initiate children we don't want // to as the parent will have detected // all module nodes already when the // master View was instantiated. if (!options.skipFindModuleNodes) { this._globals.dom = this._getDomChildren(); } // Find any DOM children with this parent domChildren = this._globals.dom.byParent && this._globals.dom.byParent[this._id]; // First we create View instances // for each child found in the DOM. // // This loop is for creating views // from children which *have* DOM context. if (domChildren) { for (i = 0, l = domChildren.length; i < l; i++) { this._add(domChildren[i]); } } // ...then we create View instances // for each child in the definition. // The internal _add method wont add // a child if one already exists on // the parent with the same _id. // // This loop is for creating fresh // child views with *no* DOM context. if (options.children) { for (i = 0, l = options.children.length; i < l; i++) { this._add(options.children[i]); this.initialize.call(this, options); }; util.extend(DefaultView.prototype, Events, { /** * Configure all options passed * into the constructor. * * @param {Object} options * @return void */ _configure: function(options) { this.parent = options.parent; this.el = options.el; this.module = options.module; this._id = options._id || options.id || util.uniqueId('dynamic'); this._children = []; this._globals = options._globals || { id: {}, domChildren: {} }; this._childHash = {}; this._data = options.data || {}; }, /** * Public Methods */ // Overwrite these yourself initialize: function() {}, onSetup: function() {}, onTeardown: function() {}, onDestroy: function() {}, /** * An internal api to add child views. * * Makes sure that the view doesn't * already have this view as a child. * * @param {[type]} options [description] */ _add: function(options) { var hasChild = !!this._childHash[options._id || options.id]; if (hasChild) return; options._globals = this._globals; options.skipFindModuleNodes = true; this.add(new View(options), { append: false }); }, /** return this; } // Merge the global variable stores. util.extend(this._globals.id, view._globals.id); // Set a refercne back to the parent. view.parent = this; util.insert(view, this._children, at); render: function(options) { var html = this._toHTML(options); var el; if (options && options.asString) return html; // Replace the contents of the current element with the // newly rendered element. We do this so that the original // view element is not replaced, and we don't loose any delegate // event listeners. el = util.toNode(html); if (this.el) { util.replaceContent(el, this.el); } else { this.el = el; } // Update the View.els for each child View. this.updateChildEls(); */ updateChildEls: function() { var domChildren = this._getDomChildren().all; for (var i = 0, l = domChildren.length; i < l; i++) { var child = domChildren[i]; var match = this.id(child._id); if (!match) continue; match.el = child.el; child: function(query) { var result = this._childHash[query]; return result[0] || result; }, /** // If this is already setup, call // `teardown` first so that we don't // duplicate event bindings and shizzle. if (this.isSetup) this.teardown(); // We trigger a `setup` event and // call the `onSetup` method. You can * itself is not going to be destroyed; * just updated in some way. * * @return {View} */ teardown: function() { for (var i = 0, l = this._children.length; i < l; i++) { this._children[i].teardown(); } this.trigger('teardown'); this.onTeardown(); this.isSetup = false; /** * Destroys all children. * * @return {FruitMachine.View} */ empty: function() { * Private Methods */ _detach: function(options) { var i; var skipEl = options && options.skipEl; // Remove the view el from the DOM if (!skipEl && this.el && this.el.parentNode) this.el.parentNode.removeChild(this.el); if (this.render === false) return; // Check we have a template if (!template) return; // Create an array to store child html in. renderData[SETTINGS.mustacheSlotArrayName] = []; var child = this._children[i]; var html = child._toHTML(options); // If no html was generated we // don't want to add a slot to the // parent's render data, so return here. if (!html) return; // Make the sub view html available // to the parent model. So that when the // parent model is rendered it can print }, /** * Creates an html attribute string. * * Options: * - `embedData` Embeds view.data() as an html attribute }, /** * Returns all child module elements. * * @return {Object} {all: {Array}, byParent: {Object}} */ _getDomChildren: function() { var els; var domChildren = { all: [], byParent: {} }; if (!this.el) return domChildren; els = this.el.getElementsByClassName(SETTINGS.slotClass); // Loop over each module node found. for (var i = 0, l = els.length; i < l; i++) { var el = els[i]; var child = { el: el, _id: el.getAttribute(SETTINGS.moduleIdAttr) || util.uniqueId('unknown'), module: el.getAttribute(SETTINGS.moduleTypeAttr) || 'undefined', parentId: el.getAttribute(SETTINGS.moduleParentAttr), data: util.extractEmbeddedData(el) }; domChildren.all.push(child); // If a parent-id was found on the // element, store a second reference // with the parent id as the key. if (child.parentId) { domChildren.byParent[child.parentId] = domChildren.byParent[child.parentId] || []; domChildren.byParent[child.parentId].push(child); } } return domChildren; } }); View.extend = function(module, protoProps, staticProps) { <MSG> Upgrades <DFF> @@ -48,7 +48,7 @@ moduleIdAttr: 'data-module-id', moduleTypeAttr: 'data-module-type', moduleDataAttr: 'data-model-data', - moduleParentAttr: 'data-parent', + parentAttr: 'data-parent', mustacheSlotArrayName: 'children', templates: undefined, debug: 0 @@ -96,6 +96,15 @@ escape: window.escape, unescape: window.unescape, + /** + * Extends the first object with + * the properties of any subsequent + * objects passed as arguments. + * + * @param {[type]} original [description] + * @return {[type]} [description] + */ + extend: function(original) { // Loop over every argument after the first. slice.call(arguments, 1).forEach(function(source) { @@ -144,6 +153,17 @@ return child; }, + /** + * Inserts a child element into the + * stated parent element. The child is + * appended unless an index is stated. + * + * @param {Element} child + * @param {Element} parent + * @param {Number} index + * @return void + */ + insertChild: function(child, parent, index) { if (!parent) return; if (typeof index !== 'undefined') { @@ -153,6 +173,16 @@ } }, + /** + * Inserts an item into an array. + * Has the option to state an index. + * + * @param {*} item + * @param {Array} array + * @param {Number} index + * @return void + */ + insert: function(item, array, index) { if (typeof index !== 'undefined') { array.splice(index, 0, item); @@ -166,25 +196,27 @@ }, /** - * Replaces the contents of the one node with contents - * of another. - * - * http://jsperf.com/replacing-element-vs-replacing-contents/3 + * Replaces the first node + * with the second. * - * @param {Element} replacement - * @param {Element} current + * @param {Element} el1 + * @param {Element} el2 * @return {Element} */ - replaceContent: function(replacement, current) { - current.innerHTML = ''; - var children = replacement.childNodes; - for (var i = 0, l = children.length; i < l; i++) { - current.appendChild(children[0]); - } - return current; + replaceEl: function(el1, el2) { + if (!el1.parentNode) return; + el1.parentNode.replaceChild(el2, el1); + return el2; }, + /** + * Turns an html string into an element + * + * @param {String} string + * @return {Element} + */ + toNode: function(string) { if (typeof string !== 'string') return string; var el = document.createElement('div'); @@ -192,6 +224,13 @@ return el.firstElementChild; }, + /** + * Generates a unique id + * + * @param {String} prefix + * @return {String} + */ + uniqueId: (function() { var counter = 1; return function(prefix) { @@ -320,6 +359,11 @@ } }; + // Mix Events into the Fruit Machine so + // plugins can be written and + // hooks listened to. + util.extend(FruitMachine, Events); + /** * VIEW */ @@ -335,45 +379,25 @@ * @constructor * @param {Object} options */ + var DefaultView = function(options) { - var domChildren, i, l; + var htmlChildren, i, l; this._configure(options); // Save a reference to this model in the globals. this._globals.id[this._id] = this; - // Don't look for module nodes in the - // view element if we have flagged not to. - // When we initiate children we don't want - // to as the parent will have detected - // all module nodes already when the - // master View was instantiated. - if (!options.skipFindModuleNodes) { - this._globals.dom = this._getDomChildren(); - } + // Search for children in the html + htmlChildren = this._childrenFromHtml(this._id); - // Find any DOM children with this parent - domChildren = this._globals.dom.byParent && this._globals.dom.byParent[this._id]; - - // First we create View instances - // for each child found in the DOM. - // - // This loop is for creating views - // from children which *have* DOM context. - if (domChildren) { - for (i = 0, l = domChildren.length; i < l; i++) { - this._add(domChildren[i]); + // If html children were found, + // turn them into Views. + if (htmlChildren) { + for (i = 0, l = htmlChildren.length; i < l; i++) { + this._add(htmlChildren[i]); } } - // ...then we create View instances - // for each child in the definition. - // The internal _add method wont add - // a child if one already exists on - // the parent with the same _id. - // - // This loop is for creating fresh - // child views with *no* DOM context. if (options.children) { for (i = 0, l = options.children.length; i < l; i++) { this._add(options.children[i]); @@ -383,54 +407,31 @@ this.initialize.call(this, options); }; - + // Extend the prototype util.extend(DefaultView.prototype, Events, { - /** - * Configure all options passed - * into the constructor. - * - * @param {Object} options - * @return void - */ - - _configure: function(options) { - this.parent = options.parent; - this.el = options.el; - this.module = options.module; - this._id = options._id || options.id || util.uniqueId('dynamic'); - this._children = []; - this._globals = options._globals || { id: {}, domChildren: {} }; - this._childHash = {}; - this._data = options.data || {}; - }, - /** * Public Methods */ // Overwrite these yourself + // inside your custom view logic. initialize: function() {}, onSetup: function() {}, onTeardown: function() {}, onDestroy: function() {}, /** - * An internal api to add child views. + * Declares whether a view has + * a child that matches a standard + * child query (id or module name). * - * Makes sure that the view doesn't - * already have this view as a child. - * - * @param {[type]} options [description] + * @param {String} query + * @return {Boolean} */ - _add: function(options) { - var hasChild = !!this._childHash[options._id || options.id]; - if (hasChild) return; - - options._globals = this._globals; - options.skipFindModuleNodes = true; - this.add(new View(options), { append: false }); + hasChild: function(query) { + return !!this.child(query); }, /** @@ -468,10 +469,13 @@ return this; } - // Merge the global variable stores. + // Dont add this child if it already exists + if (this.hasChild(view.id())) return this; + + // Merge the global id reference stores util.extend(this._globals.id, view._globals.id); - // Set a refercne back to the parent. + // Set a refercne back to the parent view.parent = this; util.insert(view, this._children, at); @@ -508,21 +512,28 @@ render: function(options) { var html = this._toHTML(options); - var el; + var asString = options && options.asString; + var newEl; + + // Check html has been generated + if ('undefined' === typeof html) return this; - if (options && options.asString) return html; + // Return html string if requested + if (asString) return html; // Replace the contents of the current element with the // newly rendered element. We do this so that the original // view element is not replaced, and we don't loose any delegate // event listeners. - el = util.toNode(html); + newEl = util.toNode(html); - if (this.el) { - util.replaceContent(el, this.el); - } else { - this.el = el; - } + // If the view has an element, + // replace it with the new element. + if (this.el) util.replaceEl(this.el, newEl); + + // Set the new rendered element + // as the view's element. + this.el = newEl; // Update the View.els for each child View. this.updateChildEls(); @@ -545,10 +556,13 @@ */ updateChildEls: function() { - var domChildren = this._getDomChildren().all; + var i, l, htmlChildren; - for (var i = 0, l = domChildren.length; i < l; i++) { - var child = domChildren[i]; + this._purgeChildrenFromHtmlCache(); + htmlChildren = this._childrenFromHtml(); + + for (i = 0, l = htmlChildren.length; i < l; i++) { + var child = htmlChildren[i]; var match = this.id(child._id); if (!match) continue; match.el = child.el; @@ -624,7 +638,7 @@ child: function(query) { var result = this._childHash[query]; - return result[0] || result; + return result ? result[0] || result : null; }, /** @@ -688,7 +702,11 @@ // If this is already setup, call // `teardown` first so that we don't // duplicate event bindings and shizzle. - if (this.isSetup) this.teardown(); + if (this.isSetup) this.teardown({ shallow: true }); + + // Trigger the beforesetup event so that + // FruitMachine plugins can hook into them + FruitMachine.trigger('beforesetup', this); // We trigger a `setup` event and // call the `onSetup` method. You can @@ -714,14 +732,27 @@ * itself is not going to be destroyed; * just updated in some way. * + * Options: + * - `shallow` Don't teardown recursively + * * @return {View} */ - teardown: function() { - for (var i = 0, l = this._children.length; i < l; i++) { - this._children[i].teardown(); + teardown: function(options) { + var shallow = options && options.shallow; + + // If the shollow options is not + // declared, run teardown recursively. + if (!shallow) { + for (var i = 0, l = this._children.length; i < l; i++) { + this._children[i].teardown(); + } } + // Trigger the beforeteardown event so that + // FruitMachine plugins can hook into them + FruitMachine.trigger('beforeteardown', this); + this.trigger('teardown'); this.onTeardown(); this.isSetup = false; @@ -733,7 +764,7 @@ /** * Destroys all children. * - * @return {FruitMachine.View} + * @return {View} */ empty: function() { @@ -801,9 +832,47 @@ * Private Methods */ + /** + * Configure all options passed + * into the constructor. + * + * @param {Object} options + * @return void + */ + + _configure: function(options) { + this.parent = options.parent; + this.el = options.el; + this.module = options.module; + this._id = options._id || options.id || util.uniqueId('dynamic'); + this._children = []; + this._globals = options._globals || { id: {} }; + this._childHash = {}; + this._data = util.extend({}, options.data); + }, + + /** + * An internal api to add child + * views. It ensures that globals + * are inherited and views with elements + * are not appends to the parent view. + * + * @param {Objecy} options + */ + + _add: function(options) { + + // Make sure the globals are passed on + // as this includes important data. + options._globals = this._globals; + + // Don't append the element into the parent element + this.add(new View(options), { append: false }); + }, + _detach: function(options) { - var i; var skipEl = options && options.skipEl; + var i; // Remove the view el from the DOM if (!skipEl && this.el && this.el.parentNode) this.el.parentNode.removeChild(this.el); @@ -847,7 +916,7 @@ if (this.render === false) return; // Check we have a template - if (!template) return; + if (!template) return ""; // Create an array to store child html in. renderData[SETTINGS.mustacheSlotArrayName] = []; @@ -857,11 +926,6 @@ var child = this._children[i]; var html = child._toHTML(options); - // If no html was generated we - // don't want to add a slot to the - // parent's render data, so return here. - if (!html) return; - // Make the sub view html available // to the parent model. So that when the // parent model is rendered it can print @@ -880,7 +944,8 @@ }, /** - * Creates an html attribute string. + * Creates an html attribute string + * for this view element. * * Options: * - `embedData` Embeds view.data() as an html attribute @@ -913,41 +978,66 @@ }, /** - * Returns all child module elements. + * Returns all child views found + * in the current View's html. * - * @return {Object} {all: {Array}, byParent: {Object}} + * @return {Array} */ - _getDomChildren: function() { - var els; - var domChildren = { all: [], byParent: {} }; - if (!this.el) return domChildren; + _childrenFromHtml: function(parentId) { + if (!this.el) return children; + var els, el, child; + var children = []; + var cache = this._globals.childrenFromHtml; + + // If a cache exists, use that + if (cache) return parentId ? cache[parentId] : cache; + + // Else, create a cache + cache = this._globals.childrenFromHtml = []; + + // Look for child elements els = this.el.getElementsByClassName(SETTINGS.slotClass); - // Loop over each module node found. + // Loop over each element found for (var i = 0, l = els.length; i < l; i++) { - var el = els[i]; - var child = { + el = els[i]; + + child = { el: el, _id: el.getAttribute(SETTINGS.moduleIdAttr) || util.uniqueId('unknown'), module: el.getAttribute(SETTINGS.moduleTypeAttr) || 'undefined', - parentId: el.getAttribute(SETTINGS.moduleParentAttr), + parentId: el.getAttribute(SETTINGS.parentAttr), data: util.extractEmbeddedData(el) }; - domChildren.all.push(child); + // If a parent id has not been + // stated, or the parentId matches + // the html attribute parent id, + // add this child to the array. + if (!parentId || parentId === child.parentId) children.push(child); - // If a parent-id was found on the - // element, store a second reference - // with the parent id as the key. - if (child.parentId) { - domChildren.byParent[child.parentId] = domChildren.byParent[child.parentId] || []; - domChildren.byParent[child.parentId].push(child); - } + // Cache this child + cache.push(child); + cache[child.parentId] = cache[child.parentId] || []; + cache[child.parentId].push(child); } - return domChildren; + return children; + }, + + /** + * Purges any cached children from html, + * so that when `childrenFromHtml` is next + * run it will search for new elements. + * + * @return void + */ + + _purgeChildrenFromHtmlCache: function() { + delete this._globals.childrenFromHtml; } + }); View.extend = function(module, protoProps, staticProps) {
211
Upgrades
121
.js
js
mit
ftlabs/fruitmachine
10062869
<NME> view.js <BEF> var fruitmachine = require('../../../../lib/'); // Require these views so that // fruitmachine registers them var LayoutA = require('../layout-a'); var ModuleApple = require('../module-apple'); var ModuleOrange = require('../module-orange'); var ModuleBanana = require('../module-banana'); module.exports = function(data) { var layout = { module: 'layout-a', children: [ { id: 'slot_1', module: 'orange' }, { id: 'slot_2', module: 'apple', data: { title: data.title } }, { id: 'slot_3', module: 'banana' } ] }; return fruitmachine(layout); }; <MSG> Merge pull request #40 from rowanbeentje/master Update docs and examples to change "data" to "model" <DFF> @@ -18,7 +18,7 @@ module.exports = function(data) { { id: 'slot_2', module: 'apple', - data: { + model: { title: data.title } },
1
Merge pull request #40 from rowanbeentje/master
1
.js
js
mit
ftlabs/fruitmachine
10062870
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062871
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062872
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062873
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062874
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062875
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062876
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062877
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062878
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062879
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062880
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062881
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062882
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062883
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062884
<NME> text.tex.latex <BEF> ADDFILE <MSG> Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42 Update to TextMateSharp 1.0.43 <DFF> @@ -0,0 +1,46 @@ +\documentclass[12pt]{article} +\usepackage{lingmacros} +\usepackage{tree-dvips} +\begin{document} + +\section*{Notes for My Paper} + +Don't forget to include examples of topicalization. +They look like this: + +{\small +\enumsentence{Topicalization from sentential subject:\\ +\shortex{7}{a John$_i$ [a & kltukl & [el & + {\bf l-}oltoir & er & ngii$_i$ & a Mary]]} +{ & {\bf R-}clear & {\sc comp} & + {\bf IR}.{\sc 3s}-love & P & him & } +{John, (it's) clear that Mary loves (him).}} +} + +\subsection*{How to handle topicalization} + +I'll just assume a tree structure like (\ex{1}). + +{\small +\enumsentence{Structure of A$'$ Projections:\\ [2ex] +\begin{tabular}[t]{cccc} + & \node{i}{CP}\\ [2ex] + \node{ii}{Spec} & &\node{iii}{C$'$}\\ [2ex] + &\node{iv}{C} & & \node{v}{SAgrP} +\end{tabular} +\nodeconnect{i}{ii} +\nodeconnect{i}{iii} +\nodeconnect{iii}{iv} +\nodeconnect{iii}{v} +} +} + +\subsection*{Mood} + +Mood changes when there is a topic, as well as when +there is WH-movement. \emph{Irrealis} is the mood when +there is a non-subject topic or WH-phrase in Comp. +\emph{Realis} is the mood when there is a subject topic +or WH-phrase. + +\end{document} \ No newline at end of file
46
Merge pull request #245 from AvaloniaUI/textmatesharp-1-0.42
0
.latex
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10062885
<NME> .travis.yml <BEF> script: - "npm test" language: node_js language: node_js node_js: - "0.10" - "0.11" sudo: false <MSG> Drop CI for old node <DFF> @@ -5,5 +5,4 @@ script: language: node_js node_js: - - "0.10" - "0.11"
0
Drop CI for old node
1
.yml
travis
mit
ftlabs/fruitmachine
10062886
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of loadjs.js in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 711 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags) ## Documentation 1. Load a single file ```javascript loadjs('/path/to/foo.js', function() { /* foo.js loaded */ }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -9,7 +9,7 @@ LoadJS is a tiny async loader for modern browsers (711 bytes). ## Introduction -LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of loadjs.js in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. +LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 711 bytes (minified + gzipped).
1
Update README.md
1
.md
md
mit
muicss/loadjs
10062887
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of loadjs.js in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 711 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags) ## Documentation 1. Load a single file ```javascript loadjs('/path/to/foo.js', function() { /* foo.js loaded */ }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -9,7 +9,7 @@ LoadJS is a tiny async loader for modern browsers (711 bytes). ## Introduction -LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of loadjs.js in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. +LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript and CSS files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 711 bytes (minified + gzipped).
1
Update README.md
1
.md
md
mit
muicss/loadjs
10062888
<NME> .travis.yml <BEF> script: - "grunt buster" language: node_js node_js: - 0.8.x before_script: - npm install -g grunt-cli sudo: false <MSG> npm test runs all tests <DFF> @@ -1,10 +1,7 @@ script: - - "grunt buster" + - "npm test" language: node_js node_js: - - 0.8.x - -before_script: - - npm install -g grunt-cli \ No newline at end of file + - 0.8.x \ No newline at end of file
2
npm test runs all tests
5
.yml
travis
mit
ftlabs/fruitmachine
10062889
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062890
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062891
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062892
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062893
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062894
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062895
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062896
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062897
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062898
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062899
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062900
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062901
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062902
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062903
<NME> TextTransformation.cs <BEF> using System; using AvaloniaEdit.Document; using AM = Avalonia.Media; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { AM.IBrush GetBrush(int color); } public IColorMap ColorMap { get; set; } public Action<Exception> ExceptionHandler { get; set; } public int ForegroundColor { get; set; } { public interface IColorMap { bool Contains(int color); IBrush GetBrush(int color); } int _foregroundBrushId; int _backgroundBrushId; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, int foregroundBrushId, int backgroundBrushId, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _foregroundBrushId = foregroundBrushId; _backgroundBrushId = backgroundBrushId; _fontStyle = fontStyle; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, ColorMap.GetBrush(ForegroundColor), ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foregroundBrushId), _colorMap.GetBrush(_backgroundBrushId), GetFontStyle(), GetFontWeight(), IsUnderline()); (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Tidy code, simplify var names, remove unused interface method <DFF> @@ -24,25 +24,24 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - bool Contains(int color); IBrush GetBrush(int color); } - int _foregroundBrushId; - int _backgroundBrushId; + int _foreground; + int _background; int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, int startOffset, int endOffset, - int foregroundBrushId, - int backgroundBrushId, + int foreground, + int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; - _foregroundBrushId = foregroundBrushId; - _backgroundBrushId = backgroundBrushId; + _foreground = foreground; + _background = background; _fontStyle = fontStyle; } @@ -67,8 +66,8 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foregroundBrushId), - _colorMap.GetBrush(_backgroundBrushId), + _colorMap.GetBrush(_foreground), + _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline());
8
Tidy code, simplify var names, remove unused interface method
9
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062904
<NME> README.md <BEF> # jsGrid Lightweight Grid jQuery Plugin [![Build Status](https://travis-ci.org/tabalinas/jsgrid.svg?branch=master)](https://travis-ci.org/tabalinas/jsgrid) Project site [js-grid.com](http://js-grid.com/) **jsGrid** is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging, sorting, and validating. jsGrid is tunable and allows to customize appearance and components. ![jsGrid lightweight client-side data grid](http://content.screencast.com/users/tabalinas/folders/Jing/media/beada891-57fc-41f3-ad77-fbacecd01d15/00000002.png) ## Table of contents * [Demos](#demos) * [Installation](#installation) * [Basic Usage](#basic-usage) * [Configuration](#configuration) * [Grid Fields](#grid-fields) * [Methods](#methods) * [Callbacks](#callbacks) * [Grid Controller](#grid-controller) * [Validation](#validation) * [Localization](#localization) * [Sorting Strategies](#sorting-strategies) * [Load Strategies](#load-strategies) * [Load Indication](#load-indication) * [Requirement](#requirement) * [Compatibility](#compatibility) ## Demos See [Demos](http://js-grid.com/demos/) on project site. Sample projects showing how to use jsGrid with the most popular backend technologies * **PHP** - https://github.com/tabalinas/jsgrid-php * **ASP.NET WebAPI** - https://github.com/tabalinas/jsgrid-webapi * **Express (NodeJS)** - https://github.com/tabalinas/jsgrid-express * **Ruby on Rail** - https://github.com/tabalinas/jsgrid-rails * **Django (Python)** - https://github.com/tabalinas/jsgrid-django ## Installation Install jsgrid with bower: ```bash $ bower install js-grid --save ``` Find jsGrid cdn links [here](https://cdnjs.com/libraries/jsgrid). ## Basic Usage Ensure that jQuery library of version 1.8.3 or later is included. Include `jsgrid.min.js`, `jsgrid-theme.min.css`, and `jsgrid.min.css` files into the web page. Create grid applying jQuery plugin `jsGrid` with grid config as follows: ```javascript $("#jsGrid").jsGrid({ width: "100%", height: "400px", filtering: true, editing: true, sorting: true, paging: true, data: db.clients, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] }); ``` ## Configuration The config object may contain following options (default values are specified below): ```javascript { fields: [], data: [], autoload: false, controller: { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, width: "auto", height: "auto", heading: true, filtering: false, inserting: false, editing: false, selecting: true, sorting: false, paging: false, pageLoading: false, insertRowLocation: "bottom", rowClass: function(item, itemIndex) { ... }, rowClick: function(args) { ... }, rowDoubleClick: function(args) { ... }, noDataContent: "Not found", confirmDeleting: true, deleteConfirm: "Are you sure?", pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", invalidNotify: function(args) { ... } invalidMessage: "Invalid data entered!", loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, loadIndicator: function(config) { ... } loadStrategy: function(config) { ... } updateOnResize: true, rowRenderer: null, headerRowRenderer: null, filterRowRenderer: null, insertRowRenderer: null, editRowRenderer: null, pagerRenderer: null } ``` ### fields An array of fields (columns) of the grid. Each field has general options and specific options depending on field type. General options peculiar to all field types: ```javascript { type: "", name: "", title: "", align: "", width: 100, visible: true, css: "", headercss: "", filtercss: "", insertcss: "", editcss: "", filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", headerTemplate: function() { ... }, itemTemplate: function(value, item) { ... }, filterTemplate: function() { ... }, insertTemplate: function() { ... }, editTemplate: function(value, item) { ... }, filterValue: function() { ... }, insertValue: function() { ... }, editValue: function() { ... }, cellRenderer: null, validate: null } ``` - **type** is a string key of field (`"text"|"number"|"checkbox"|"select"|"textarea"|"control"`) in fields registry `jsGrid.fields` (the registry can be easily extended with custom field types). - **name** is a property of data item associated with the column. - **title** is a text to be displayed in the header of the column. If `title` is not specified, the `name` will be used instead. - **align** is alignment of text in the cell. Accepts following values `"left"|"center"|"right"`. - **width** is a width of the column. - **visible** is a boolean specifying whether to show a column or not. (version added: 1.3) - **css** is a string representing css classes to be attached to the table cell. - **headercss** is a string representing css classes to be attached to the table header cell. If not specified, then **css** is attached instead. - **filtercss** is a string representing css classes to be attached to the table filter row cell. If not specified, then **css** is attached instead. - **insertcss** is a string representing css classes to be attached to the table insert row cell. If not specified, then **css** is attached instead. - **editcss** is a string representing css classes to be attached to the table edit row cell. If not specified, then **css** is attached instead. - **filtering** is a boolean specifying whether or not column has filtering (`filterTemplate()` is rendered and `filterValue()` is included in load filter object). - **inserting** is a boolean specifying whether or not column has inserting (`insertTemplate()` is rendered and `insertValue()` is included in inserting item). - **editing** is a boolean specifying whether or not column has editing (`editTemplate()` is rendered and `editValue()` is included in editing item). - **sorting** is a boolean specifying whether or not column has sorting ability. - **sorter** is a string or a function specifying how to sort item by the field. The string is a key of sorting strategy in the registry `jsGrid.sortStrategies` (the registry can be easily extended with custom sorting functions). Sorting function has the signature `function(value1, value2) { return -1|0|1; }`. - **headerTemplate** is a function to create column header content. It should return markup as string, DomNode or jQueryElement. - **itemTemplate** is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterTemplate** is a function to create filter row cell content. It should return markup as string, DomNode or jQueryElement. - **insertTemplate** is a function to create insert row cell content. It should return markup as string, DomNode or jQueryElement. - **editTemplate** is a function to create cell content of editing row. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterValue** is a function returning the value of filter property associated with the column. - **insertValue** is a function returning the value of inserting item property associated with the column. - **editValue** is a function returning the value of editing item property associated with the column. - **cellRenderer** is a function to customize cell rendering. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. The function should return markup as a string, jQueryElement or DomNode representing table cell `td`. - **validate** is a string as validate rule name or validation function or a validation configuration object or an array of validation configuration objects. Read more details about validation in the [Validation section](#validation). Specific field options depends on concrete field type. Read about build-in fields in [Grid Fields](#grid-fields) section. ### data An array of items to be displayed in the grid. The option should be used to provide static data. Use the `controller` option to provide non static data. ### autoload (default `false`) A boolean value specifying whether `controller.loadData` will be called when grid is rendered. ### controller An object or function returning an object with the following structure: ```javascript { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop } ``` - **loadData** is a function returning an array of data or jQuery promise that will be resolved with an array of data (when `pageLoading` is `true` instead of object the structure `{ data: [items], itemsCount: [total items count] }` should be returned). Accepts filter parameter including current filter options and paging parameters when `pageLoading` is `true`. - **insertItem** is a function returning inserted item or jQuery promise that will be resolved with inserted item. Accepts inserting item object. - **updateItem** is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object. - **deleteItem** is a function deleting item. Returns jQuery promise that will be resolved when deletion is completed. Accepts deleting item object. Read more about controller interface in [Grid Controller](#grid-controller) section. ### width (default: `"auto"`) Specifies the overall width of the grid. Accepts all value types accepting by `jQuery.width`. ### height (default: `"auto"`) Specifies the overall height of the grid including the pager. Accepts all value types accepting by `jQuery.height`. ### heading (default: `true`) A boolean value specifies whether to show grid header or not. ### filtering (default: `false`) A boolean value specifies whether to show filter row or not. ### inserting (default: `false`) A boolean value specifies whether to show inserting row or not. ### editing (default: `false`) A boolean value specifies whether editing is allowed. ### selecting (default: `true`) A boolean value specifies whether to highlight grid rows on hover. ### sorting (default: `false`) A boolean value specifies whether sorting is allowed. ### paging (default: `false`) A boolean value specifies whether data is displayed by pages. ### pageLoading (default: `false`) A boolean value specifies whether to load data by page. When `pageLoading` is `true` the `loadData` method of controller accepts `filter` parameter with two additional properties `pageSize` and `pageIndex`. ### insertRowLocation (default: `"bottom"`) Specifies the location of an inserted row within the grid. When `insertRowLocation` is `"bottom"` the new row will appear at the bottom of the grid. When set to `"top"`, the new row will appear at the top. ### rowClass A string or a function specifying row css classes. A string contains classes separated with spaces. A function has signature `function(item, itemIndex)`. It accepts the data item and index of the item. It should returns a string containing classes separated with spaces. ### rowClick A function handling row click. Accepts single argument with following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` By default `rowClick` performs row editing when `editing` is `true`. ### rowDoubleClick A function handling row double click. Accepts single argument with the following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` ### noDataContent (default `"Not found"`) A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when `data` is an empty array. ### confirmDeleting (default `true`) A boolean value specifying whether to ask user to confirm item deletion. ### deleteConfirm (default `"Are you sure?"`) A string or a function returning string specifying delete confirmation message to be displayed to the user. A function has the signature `function(item)` and accepts item to be deleted. ### pagerContainer (default `null`) A jQueryElement or DomNode to specify where to render a pager. Used for external pager rendering. When it is equal to `null`, the pager is rendered at the bottom of the grid. ### pageIndex (default `1`) An integer value specifying current page index. Applied only when `paging` is `true`. ### pageSize (default `20`) An integer value specifying the amount of items on the page. Applied only when `paging` is `true`. ### pageButtonCount (default `15`) An integer value specifying the maximum amount of page buttons to be displayed in the pager. ### pagerFormat A string specifying pager format. The default value is `"Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}"` There are placeholders that can be used in the format: ```javascript {first} // link to first page {prev} // link to previous page {pages} // page links {next} // link to next page {last} // link to last page {pageIndex} // current page index {pageCount} // total amount of pages {itemCount} // total amount of items ``` ### pageNextText (default `"Next"`) A string specifying the text of the link to the next page. ### pagePrevText (default `"Prev"`) A string specifying the text of the link to the previous page. ### pageFirstText (default `"First"`) A string specifying the text of the link to the first page. ### pageLastText (default `"Last"`) A string specifying the text of the link to the last page. ### pageNavigatorNextText (default `"..."`) A string specifying the text of the link to move to next set of page links, when total amount of pages more than `pageButtonCount`. ### pageNavigatorPrevText (default `"..."`) A string specifying the text of the link to move to previous set of page links, when total amount of pages more than `pageButtonCount`. ### invalidMessage (default `"Invalid data entered!"`) A string specifying the text of the alert message, when invalid data was entered. ### invalidNotify A function triggered, when invalid data was entered. By default all violated validators messages are alerted. The behavior can be customized by providing custom function. The function accepts a single argument with the following structure: ```javascript { item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` In the following example error messages are printed in the console instead of alerting: ```javascript $("#grid").jsGrid({ ... invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.field + ": " + error.message; }); console.log(messages); } ... }); ``` ### loadIndication (default `true`) A boolean value specifying whether to show loading indication during controller operations execution. ### loadIndicationDelay (default `500`) An integer value specifying the delay in ms before showing load indication. Applied only when `loadIndication` is `true`. ### loadMessage (default `"Please, wait..."`) A string specifying the text of loading indication panel. Applied only when `loadIndication` is `true`. ### loadShading (default `true`) A boolean value specifying whether to show overlay (shader) over grid content during loading indication. Applied only when `loadIndication` is `true`. ### loadIndicator An object or a function returning an object representing grid load indicator. Load indicator could be any js object supporting two methods `show` and `hide`. `show` is called on each loading start. `hide` method is called on each loading finish. Read more about custom load indicator in the [Load Indication](#load-indication) section. ### loadStrategy An object or a function returning an object representing grid load strategy. Load strategy defines behavior of the grid after loading data (any interaction with grid controller methods including data manipulation like inserting, updating and removing). There are two build-in load strategies: `DirectLoadingStrategy` and `PageLoadingStrategy`. Load strategy depends on `pageLoading` option value. For advanced scenarios custom load strategy can be provided. Read more about custom load strategies in the [Load Strategies](#load-strategies) section. ### updateOnResize (default `true`) A boolean value specifying whether to refresh grid on window resize event. ### rowRenderer (default `null`) A function to customize row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### headerRowRenderer (default `null`) A function to customize grid header row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### filterRowRenderer (default `null`) A function to customize grid filter row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### insertRowRenderer (default `null`) A function to customize grid inserting row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### editRowRenderer (default `null`) A function to customize editing row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### pagerRenderer (default `null`) > version added: 1.2 A function to customize pager rendering. The function accepts a single argument with the following structure: ```javascript { pageIndex, // index of the currently opened page pageCount // total amount of grid pages } ``` The function should return markup as a string, jQueryElement or DomNode representing the pager. If `pagerRenderer` is specified, then `pagerFormat` option will be ignored. ## Grid Fields All fields supporting by grid are stored in `jsGrid.fields` object, where key is a type of the field and the value is the field class. `jsGrid.fields` contains following build-in fields: ```javascript { text: { ... }, // simple text input number: { ... }, // number input select: { ... }, // select control checkbox: { ... }, // checkbox input textarea: { ... }, // textarea control (renders textarea for inserting and editing and text input for filtering) control: { ... } // control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row } ``` Each build-in field can be easily customized with general configuration properties described in [fields](#fields) section and custom field-specific properties described below. ### text Text field renders `<input type="text">` in filter, inserting and editing rows. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### number Number field renders `<input type="number">` in filter, inserting and editing rows. Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "right", // right text alignment readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### select Select field renders `<select>` control in filter, inserting and editing rows. Custom properties: ```javascript { align: "center", // center text alignment autosearch: true, // triggers searching when the user changes the selected item in the filter items: [], // an array of items for select valueField: "", // name of property of item to be used as value textField: "", // name of property of item to be used as displaying value selectedIndex: -1, // index of selected item by default valueType: "number|string", // the data type of the value readOnly: false // a boolean defines whether select is readonly (added in v1.4) } ``` If valueField is not defined, then the item index is used instead. If textField is not defined, then item itself is used to display value. For instance the simple select field config may look like: ```javascript { name: "Country", type: "select", items: [ "", "United States", "Canada", "United Kingdom" ] } ``` or more complex with items as objects: ```javascript { name: "Country", type: "select" items: [ { Name: "", Id: 0 }, { Name: "United States", Id: 1 }, { Name: "Canada", Id: 2 }, { Name: "United Kingdom", Id: 3 } ], valueField: "Id", textField: "Name" } ``` `valueType` defines whether the field value should be converted to a number or returned as a string. The value of the option is determined automatically depending on the data type of `valueField` of the first item, but it can be overridden. ### checkbox Checkbox field renders `<input type="checkbox">` in filter, inserting and editing rows. Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "center", // center text alignment autosearch: true // triggers searching when the user clicks checkbox in filter } ``` ### textarea Textarea field renders `<textarea>` in inserting and editing rows and `<input type="text">` in filter row. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether textarea is readonly (added in v1.4) } ``` ### control Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. It also renders button switching between filtering and searching in header row. Custom properties: ```javascript { editButton: true, // show edit button deleteButton: true, // show delete button clearFilterButton: true, // show clear filter button modeSwitchButton: true, // show switching filtering/inserting button align: "center", // center content alignment width: 50, // default column width is 50px filtering: false, // disable filtering for column inserting: false, // disable inserting for column editing: false, // disable editing for column sorting: false, // disable sorting for column searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode editButtonTooltip: "Edit", // tooltip of edit item button deleteButtonTooltip: "Delete", // tooltip of delete item button searchButtonTooltip: "Search", // tooltip of search button clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button insertButtonTooltip: "Insert", // tooltip of insert button updateButtonTooltip: "Update", // tooltip of update item button cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button } ``` ### Custom Field If you need a completely custom field, the object `jsGrid.fields` can be easily extended. In this example we define new grid field `date`: ```javascript var MyDateField = function(config) { jsGrid.Field.call(this, config); }; MyDateField.prototype = new jsGrid.Field({ css: "date-field", // redefine general property 'css' align: "center", // redefine general property 'align' myCustomProperty: "foo", // custom property sorter: function(date1, date2) { return new Date(date1) - new Date(date2); }, itemTemplate: function(value) { return new Date(value).toDateString(); }, insertTemplate: function(value) { return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); }, editTemplate: function(value) { return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); }, insertValue: function() { return this._insertPicker.datepicker("getDate").toISOString(); }, editValue: function() { return this._editPicker.datepicker("getDate").toISOString(); } }); jsGrid.fields.date = MyDateField; ``` To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. Here `itemTemplate` just returns the string representation of a date. `insertTemplate` and `editTemplate` create jQuery UI datePicker for inserting and editing row. Of course jquery ui library should be included to make it work. `insertValue` and `editValue` return date to insert and update items accordingly. We also defined date specific sorter. Now, our new field `date` can be used in the grid config as follows: ```javascript { fields: [ ... { type: "date", myCustomProperty: "bar" }, ... ] } ``` ## Methods jsGrid methods could be called with `jsGrid` jQuery plugin or directly. To use jsGrid plugin to call a method, just call `jsGrid` with method name and required parameters as next arguments: ```javascript // calling method with jQuery plugin $("#grid").jsGrid("methodName", param1, param2); ``` To call method directly you need to retrieve grid instance or just create grid with the constructor: ```javascript // retrieve grid instance from element data var grid = $("#grid").data("JSGrid"); // create grid with the constructor var grid = new jsGrid.Grid($("#grid"), { ... }); // call method directly grid.methodName(param1, param2); ``` ### cancelEdit() Cancels row editing. ```javascript $("#grid").jsGrid("cancelEdit"); ``` ### clearFilter(): `Promise` Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed. ```javascript $("#grid").jsGrid("clearFilter").done(function() { console.log("filtering completed"); }); ``` ### clearInsert() Clears current inserting row. ```javascript $("#grid").jsGrid("clearInsert"); ``` ### deleteItem(item|$row|rowNode): `Promise` Removes specified row from the grid. Returns jQuery promise resolved when deletion is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // delete row by item reference $("#grid").jsGrid("deleteItem", item); // delete row by jQueryElement $("#grid").jsGrid("deleteItem", $(".specific-row")); // delete row by DomNode $("#grid").jsGrid("deleteItem", rowNode); ``` ### destroy() Destroys the grid and brings the Node to its original state. ```javascript $("#grid").jsGrid("destroy"); ``` ### editItem(item|$row|rowNode) Sets grid editing row. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // edit row by item reference $("#grid").jsGrid("editItem", item); // edit row by jQueryElement $("#grid").jsGrid("editItem", $(".specific-row")); // edit row by DomNode $("#grid").jsGrid("editItem", rowNode); ``` ### getFilter(): `Object` Get grid filter as a plain object. ```javascript var filter = $("#grid").jsGrid("getFilter"); ``` ### getSorting(): `Object` > version added: 1.2 Get grid current sorting params as a plain object with the following format: ```javascript { field, // the name of the field by which grid is sorted order // 'asc' or 'desc' depending on sort order } ``` ```javascript var sorting = $("#grid").jsGrid("getSorting"); ``` ### fieldOption(fieldName|fieldIndex, optionName, [optionValue]) > version added: 1.3 Gets or sets the value of a field option. **fieldName|fieldIndex** is the name or the index of the field to get/set the option value (if the grid contains more than one field with the same name, the first field will be used). **optionName** is the name of the field option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the field option `optionName` will be returned. ```javascript // hide the field "ClientName" $("#grid").jsGrid("fieldOption", "ClientName", "visible", false); // get width of the 2nd field var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width"); ``` ### insertItem([item]): `Promise` Inserts row into the grid based on item. Returns jQuery promise resolved when insertion is completed. **item** is the item to pass to `controller.insertItem`. If `item` is not specified the data from inserting row will be inserted. ```javascript // insert item from inserting row $("#grid").jsGrid("insertItem"); // insert item $("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() { console.log("insertion completed"); }); ``` ### loadData([filter]): `Promise` Loads data calling corresponding `controller.loadData` method. Returns jQuery promise resolved when data loading is completed. It preserves current sorting and paging unlike the `search` method . **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // load data with current grid filter $("#grid").jsGrid("loadData"); // loadData with custom filter $("#grid").jsGrid("loadData", { Name: "John" }).done(function() { console.log("data loaded"); }); ``` ### exportData([options]) Transforms the grid data into the specified output type. Output can be formatted, filtered or modified by providing options. Currently only supports CSV output. ```javascript //Basic export var csv = $("#grid").jsGrid("exportData"); //Full Options var csv = $("#grid").jsGrid("exportData", { type: "csv", //Only CSV supported subset: "all" | "visible", //Visible will only output the currently displayed page delimiter: "|", //If using csv, the character to seperate fields includeHeaders: true, //Include header row in output encapsulate: true, //Surround each field with qoutation marks; needed for some systems newline: "\r\n", //Newline character to use //Takes each item and returns true if it should be included in output. //Executed only on the records within the given subset above. filter: function(item){return true}, //Transformations are a way to modify the display value of the output. //Provide a key of the field name, and a function that takes the current value. transformations: { "Married": function(value){ if (value === true){ return "Yes" } else{ return "No" } } } }); ``` ### openPage(pageIndex) Opens the page of specified index. **pageIndex** is one-based index of the page to open. The value should be in range from 1 to [total amount of pages]. ### option(optionName, [optionValue]) Gets or sets the value of an option. **optionName** is the name of the option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the option `optionName` will be returned. ```javascript // turn off paging $("#grid").jsGrid("option", "paging", false); // get current page index var pageIndex = $("#grid").jsGrid("option", "pageIndex"); ``` ### refresh() Refreshes the grid. Renders the grid body and pager content, recalculates sizes. ```javascript $("#grid").jsGrid("refresh"); ``` ### render(): `Promise` Performs complete grid rendering. If option `autoload` is `true` calls `controller.loadData`. The state of the grid like current page and sorting is retained. Returns jQuery promise resolved when data loading is completed. If auto-loading is disabled the promise is instantly resolved. ```javascript $("#grid").jsGrid("render").done(function() { console.log("rendering completed and data loaded"); }); ``` ### reset() Resets the state of the grid. Goes to the first data page, resets sorting, and then calls `refresh`. ```javascript $("#grid").jsGrid("reset"); ``` ### rowByItem(item): `jQueryElement` > version added: 1.3 Gets the row jQuery element corresponding to the item. **item** is the item corresponding to the row. ```javascript var $row = $("#grid").jsGrid("rowByItem", item); ``` ### search([filter]): `Promise` Performs filtering of the grid. Returns jQuery promise resolved when data loading is completed. It resets current sorting and paging unlike the `loadData` method. **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // search with current grid filter $("#grid").jsGrid("search"); // search with custom filter $("#grid").jsGrid("search", { Name: "John" }).done(function() { console.log("filtering completed"); }); ``` ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showPrevPages"); ``` ### showNextPages() Shows next set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ``` ## Callbacks jsGrid allows to specify a callback function to be executed on a particular event. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid onError: function(args) {}, // on fail of any controller call onOptionChanging: function(args) {}, // before changing the grid option onOptionChanged: function(args) {}, // after changing the grid option onPageChanged: function(args) {}, // after changing the current page onRefreshing: function(args) {}, // before grid refresh onRefreshed: function(args) {}, // after grid refresh } ``` ### onDataLoading Fires before data loading. Has the following arguments: ```javascript { grid // grid instance filter // loading filter object } ``` #### Cancel Data Loading > version added: 1.2 To cancel data loading set `args.cancel = true`. In the following example loading is canceled when the filter has empty 'name' field: ```javascript $("#grid").jsGrid({ ... onDataLoading: function(args) { // cancel loading data if 'name' is empty if(args.filter.name === "") { args.cancel = true; } } }); ``` ### onDataLoaded Fires after data loading. Has the following arguments: ```javascript { grid // grid instance data // load result (array of items or data structure for loading by page scenario) } ``` In the following example the loaded data is written to the browser console. ```javascript $("#grid").jsGrid({ ... onDataLoaded: function(args) { console.log(args.data); } }); ``` ### onInit > version added: 1.5 Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a string regexp in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The
1
Clarify use of regexp for pattern validator
1
.md
md
mit
tabalinas/jsgrid
10062905
<NME> README.md <BEF> # jsGrid Lightweight Grid jQuery Plugin [![Build Status](https://travis-ci.org/tabalinas/jsgrid.svg?branch=master)](https://travis-ci.org/tabalinas/jsgrid) Project site [js-grid.com](http://js-grid.com/) **jsGrid** is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging, sorting, and validating. jsGrid is tunable and allows to customize appearance and components. ![jsGrid lightweight client-side data grid](http://content.screencast.com/users/tabalinas/folders/Jing/media/beada891-57fc-41f3-ad77-fbacecd01d15/00000002.png) ## Table of contents * [Demos](#demos) * [Installation](#installation) * [Basic Usage](#basic-usage) * [Configuration](#configuration) * [Grid Fields](#grid-fields) * [Methods](#methods) * [Callbacks](#callbacks) * [Grid Controller](#grid-controller) * [Validation](#validation) * [Localization](#localization) * [Sorting Strategies](#sorting-strategies) * [Load Strategies](#load-strategies) * [Load Indication](#load-indication) * [Requirement](#requirement) * [Compatibility](#compatibility) ## Demos See [Demos](http://js-grid.com/demos/) on project site. Sample projects showing how to use jsGrid with the most popular backend technologies * **PHP** - https://github.com/tabalinas/jsgrid-php * **ASP.NET WebAPI** - https://github.com/tabalinas/jsgrid-webapi * **Express (NodeJS)** - https://github.com/tabalinas/jsgrid-express * **Ruby on Rail** - https://github.com/tabalinas/jsgrid-rails * **Django (Python)** - https://github.com/tabalinas/jsgrid-django ## Installation Install jsgrid with bower: ```bash $ bower install js-grid --save ``` Find jsGrid cdn links [here](https://cdnjs.com/libraries/jsgrid). ## Basic Usage Ensure that jQuery library of version 1.8.3 or later is included. Include `jsgrid.min.js`, `jsgrid-theme.min.css`, and `jsgrid.min.css` files into the web page. Create grid applying jQuery plugin `jsGrid` with grid config as follows: ```javascript $("#jsGrid").jsGrid({ width: "100%", height: "400px", filtering: true, editing: true, sorting: true, paging: true, data: db.clients, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] }); ``` ## Configuration The config object may contain following options (default values are specified below): ```javascript { fields: [], data: [], autoload: false, controller: { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, width: "auto", height: "auto", heading: true, filtering: false, inserting: false, editing: false, selecting: true, sorting: false, paging: false, pageLoading: false, insertRowLocation: "bottom", rowClass: function(item, itemIndex) { ... }, rowClick: function(args) { ... }, rowDoubleClick: function(args) { ... }, noDataContent: "Not found", confirmDeleting: true, deleteConfirm: "Are you sure?", pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", invalidNotify: function(args) { ... } invalidMessage: "Invalid data entered!", loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, loadIndicator: function(config) { ... } loadStrategy: function(config) { ... } updateOnResize: true, rowRenderer: null, headerRowRenderer: null, filterRowRenderer: null, insertRowRenderer: null, editRowRenderer: null, pagerRenderer: null } ``` ### fields An array of fields (columns) of the grid. Each field has general options and specific options depending on field type. General options peculiar to all field types: ```javascript { type: "", name: "", title: "", align: "", width: 100, visible: true, css: "", headercss: "", filtercss: "", insertcss: "", editcss: "", filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", headerTemplate: function() { ... }, itemTemplate: function(value, item) { ... }, filterTemplate: function() { ... }, insertTemplate: function() { ... }, editTemplate: function(value, item) { ... }, filterValue: function() { ... }, insertValue: function() { ... }, editValue: function() { ... }, cellRenderer: null, validate: null } ``` - **type** is a string key of field (`"text"|"number"|"checkbox"|"select"|"textarea"|"control"`) in fields registry `jsGrid.fields` (the registry can be easily extended with custom field types). - **name** is a property of data item associated with the column. - **title** is a text to be displayed in the header of the column. If `title` is not specified, the `name` will be used instead. - **align** is alignment of text in the cell. Accepts following values `"left"|"center"|"right"`. - **width** is a width of the column. - **visible** is a boolean specifying whether to show a column or not. (version added: 1.3) - **css** is a string representing css classes to be attached to the table cell. - **headercss** is a string representing css classes to be attached to the table header cell. If not specified, then **css** is attached instead. - **filtercss** is a string representing css classes to be attached to the table filter row cell. If not specified, then **css** is attached instead. - **insertcss** is a string representing css classes to be attached to the table insert row cell. If not specified, then **css** is attached instead. - **editcss** is a string representing css classes to be attached to the table edit row cell. If not specified, then **css** is attached instead. - **filtering** is a boolean specifying whether or not column has filtering (`filterTemplate()` is rendered and `filterValue()` is included in load filter object). - **inserting** is a boolean specifying whether or not column has inserting (`insertTemplate()` is rendered and `insertValue()` is included in inserting item). - **editing** is a boolean specifying whether or not column has editing (`editTemplate()` is rendered and `editValue()` is included in editing item). - **sorting** is a boolean specifying whether or not column has sorting ability. - **sorter** is a string or a function specifying how to sort item by the field. The string is a key of sorting strategy in the registry `jsGrid.sortStrategies` (the registry can be easily extended with custom sorting functions). Sorting function has the signature `function(value1, value2) { return -1|0|1; }`. - **headerTemplate** is a function to create column header content. It should return markup as string, DomNode or jQueryElement. - **itemTemplate** is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterTemplate** is a function to create filter row cell content. It should return markup as string, DomNode or jQueryElement. - **insertTemplate** is a function to create insert row cell content. It should return markup as string, DomNode or jQueryElement. - **editTemplate** is a function to create cell content of editing row. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterValue** is a function returning the value of filter property associated with the column. - **insertValue** is a function returning the value of inserting item property associated with the column. - **editValue** is a function returning the value of editing item property associated with the column. - **cellRenderer** is a function to customize cell rendering. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. The function should return markup as a string, jQueryElement or DomNode representing table cell `td`. - **validate** is a string as validate rule name or validation function or a validation configuration object or an array of validation configuration objects. Read more details about validation in the [Validation section](#validation). Specific field options depends on concrete field type. Read about build-in fields in [Grid Fields](#grid-fields) section. ### data An array of items to be displayed in the grid. The option should be used to provide static data. Use the `controller` option to provide non static data. ### autoload (default `false`) A boolean value specifying whether `controller.loadData` will be called when grid is rendered. ### controller An object or function returning an object with the following structure: ```javascript { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop } ``` - **loadData** is a function returning an array of data or jQuery promise that will be resolved with an array of data (when `pageLoading` is `true` instead of object the structure `{ data: [items], itemsCount: [total items count] }` should be returned). Accepts filter parameter including current filter options and paging parameters when `pageLoading` is `true`. - **insertItem** is a function returning inserted item or jQuery promise that will be resolved with inserted item. Accepts inserting item object. - **updateItem** is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object. - **deleteItem** is a function deleting item. Returns jQuery promise that will be resolved when deletion is completed. Accepts deleting item object. Read more about controller interface in [Grid Controller](#grid-controller) section. ### width (default: `"auto"`) Specifies the overall width of the grid. Accepts all value types accepting by `jQuery.width`. ### height (default: `"auto"`) Specifies the overall height of the grid including the pager. Accepts all value types accepting by `jQuery.height`. ### heading (default: `true`) A boolean value specifies whether to show grid header or not. ### filtering (default: `false`) A boolean value specifies whether to show filter row or not. ### inserting (default: `false`) A boolean value specifies whether to show inserting row or not. ### editing (default: `false`) A boolean value specifies whether editing is allowed. ### selecting (default: `true`) A boolean value specifies whether to highlight grid rows on hover. ### sorting (default: `false`) A boolean value specifies whether sorting is allowed. ### paging (default: `false`) A boolean value specifies whether data is displayed by pages. ### pageLoading (default: `false`) A boolean value specifies whether to load data by page. When `pageLoading` is `true` the `loadData` method of controller accepts `filter` parameter with two additional properties `pageSize` and `pageIndex`. ### insertRowLocation (default: `"bottom"`) Specifies the location of an inserted row within the grid. When `insertRowLocation` is `"bottom"` the new row will appear at the bottom of the grid. When set to `"top"`, the new row will appear at the top. ### rowClass A string or a function specifying row css classes. A string contains classes separated with spaces. A function has signature `function(item, itemIndex)`. It accepts the data item and index of the item. It should returns a string containing classes separated with spaces. ### rowClick A function handling row click. Accepts single argument with following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` By default `rowClick` performs row editing when `editing` is `true`. ### rowDoubleClick A function handling row double click. Accepts single argument with the following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` ### noDataContent (default `"Not found"`) A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when `data` is an empty array. ### confirmDeleting (default `true`) A boolean value specifying whether to ask user to confirm item deletion. ### deleteConfirm (default `"Are you sure?"`) A string or a function returning string specifying delete confirmation message to be displayed to the user. A function has the signature `function(item)` and accepts item to be deleted. ### pagerContainer (default `null`) A jQueryElement or DomNode to specify where to render a pager. Used for external pager rendering. When it is equal to `null`, the pager is rendered at the bottom of the grid. ### pageIndex (default `1`) An integer value specifying current page index. Applied only when `paging` is `true`. ### pageSize (default `20`) An integer value specifying the amount of items on the page. Applied only when `paging` is `true`. ### pageButtonCount (default `15`) An integer value specifying the maximum amount of page buttons to be displayed in the pager. ### pagerFormat A string specifying pager format. The default value is `"Pages: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} of {pageCount}"` There are placeholders that can be used in the format: ```javascript {first} // link to first page {prev} // link to previous page {pages} // page links {next} // link to next page {last} // link to last page {pageIndex} // current page index {pageCount} // total amount of pages {itemCount} // total amount of items ``` ### pageNextText (default `"Next"`) A string specifying the text of the link to the next page. ### pagePrevText (default `"Prev"`) A string specifying the text of the link to the previous page. ### pageFirstText (default `"First"`) A string specifying the text of the link to the first page. ### pageLastText (default `"Last"`) A string specifying the text of the link to the last page. ### pageNavigatorNextText (default `"..."`) A string specifying the text of the link to move to next set of page links, when total amount of pages more than `pageButtonCount`. ### pageNavigatorPrevText (default `"..."`) A string specifying the text of the link to move to previous set of page links, when total amount of pages more than `pageButtonCount`. ### invalidMessage (default `"Invalid data entered!"`) A string specifying the text of the alert message, when invalid data was entered. ### invalidNotify A function triggered, when invalid data was entered. By default all violated validators messages are alerted. The behavior can be customized by providing custom function. The function accepts a single argument with the following structure: ```javascript { item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` In the following example error messages are printed in the console instead of alerting: ```javascript $("#grid").jsGrid({ ... invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.field + ": " + error.message; }); console.log(messages); } ... }); ``` ### loadIndication (default `true`) A boolean value specifying whether to show loading indication during controller operations execution. ### loadIndicationDelay (default `500`) An integer value specifying the delay in ms before showing load indication. Applied only when `loadIndication` is `true`. ### loadMessage (default `"Please, wait..."`) A string specifying the text of loading indication panel. Applied only when `loadIndication` is `true`. ### loadShading (default `true`) A boolean value specifying whether to show overlay (shader) over grid content during loading indication. Applied only when `loadIndication` is `true`. ### loadIndicator An object or a function returning an object representing grid load indicator. Load indicator could be any js object supporting two methods `show` and `hide`. `show` is called on each loading start. `hide` method is called on each loading finish. Read more about custom load indicator in the [Load Indication](#load-indication) section. ### loadStrategy An object or a function returning an object representing grid load strategy. Load strategy defines behavior of the grid after loading data (any interaction with grid controller methods including data manipulation like inserting, updating and removing). There are two build-in load strategies: `DirectLoadingStrategy` and `PageLoadingStrategy`. Load strategy depends on `pageLoading` option value. For advanced scenarios custom load strategy can be provided. Read more about custom load strategies in the [Load Strategies](#load-strategies) section. ### updateOnResize (default `true`) A boolean value specifying whether to refresh grid on window resize event. ### rowRenderer (default `null`) A function to customize row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### headerRowRenderer (default `null`) A function to customize grid header row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### filterRowRenderer (default `null`) A function to customize grid filter row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### insertRowRenderer (default `null`) A function to customize grid inserting row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### editRowRenderer (default `null`) A function to customize editing row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### pagerRenderer (default `null`) > version added: 1.2 A function to customize pager rendering. The function accepts a single argument with the following structure: ```javascript { pageIndex, // index of the currently opened page pageCount // total amount of grid pages } ``` The function should return markup as a string, jQueryElement or DomNode representing the pager. If `pagerRenderer` is specified, then `pagerFormat` option will be ignored. ## Grid Fields All fields supporting by grid are stored in `jsGrid.fields` object, where key is a type of the field and the value is the field class. `jsGrid.fields` contains following build-in fields: ```javascript { text: { ... }, // simple text input number: { ... }, // number input select: { ... }, // select control checkbox: { ... }, // checkbox input textarea: { ... }, // textarea control (renders textarea for inserting and editing and text input for filtering) control: { ... } // control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row } ``` Each build-in field can be easily customized with general configuration properties described in [fields](#fields) section and custom field-specific properties described below. ### text Text field renders `<input type="text">` in filter, inserting and editing rows. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### number Number field renders `<input type="number">` in filter, inserting and editing rows. Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "right", // right text alignment readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### select Select field renders `<select>` control in filter, inserting and editing rows. Custom properties: ```javascript { align: "center", // center text alignment autosearch: true, // triggers searching when the user changes the selected item in the filter items: [], // an array of items for select valueField: "", // name of property of item to be used as value textField: "", // name of property of item to be used as displaying value selectedIndex: -1, // index of selected item by default valueType: "number|string", // the data type of the value readOnly: false // a boolean defines whether select is readonly (added in v1.4) } ``` If valueField is not defined, then the item index is used instead. If textField is not defined, then item itself is used to display value. For instance the simple select field config may look like: ```javascript { name: "Country", type: "select", items: [ "", "United States", "Canada", "United Kingdom" ] } ``` or more complex with items as objects: ```javascript { name: "Country", type: "select" items: [ { Name: "", Id: 0 }, { Name: "United States", Id: 1 }, { Name: "Canada", Id: 2 }, { Name: "United Kingdom", Id: 3 } ], valueField: "Id", textField: "Name" } ``` `valueType` defines whether the field value should be converted to a number or returned as a string. The value of the option is determined automatically depending on the data type of `valueField` of the first item, but it can be overridden. ### checkbox Checkbox field renders `<input type="checkbox">` in filter, inserting and editing rows. Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "center", // center text alignment autosearch: true // triggers searching when the user clicks checkbox in filter } ``` ### textarea Textarea field renders `<textarea>` in inserting and editing rows and `<input type="text">` in filter row. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether textarea is readonly (added in v1.4) } ``` ### control Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. It also renders button switching between filtering and searching in header row. Custom properties: ```javascript { editButton: true, // show edit button deleteButton: true, // show delete button clearFilterButton: true, // show clear filter button modeSwitchButton: true, // show switching filtering/inserting button align: "center", // center content alignment width: 50, // default column width is 50px filtering: false, // disable filtering for column inserting: false, // disable inserting for column editing: false, // disable editing for column sorting: false, // disable sorting for column searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode editButtonTooltip: "Edit", // tooltip of edit item button deleteButtonTooltip: "Delete", // tooltip of delete item button searchButtonTooltip: "Search", // tooltip of search button clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button insertButtonTooltip: "Insert", // tooltip of insert button updateButtonTooltip: "Update", // tooltip of update item button cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button } ``` ### Custom Field If you need a completely custom field, the object `jsGrid.fields` can be easily extended. In this example we define new grid field `date`: ```javascript var MyDateField = function(config) { jsGrid.Field.call(this, config); }; MyDateField.prototype = new jsGrid.Field({ css: "date-field", // redefine general property 'css' align: "center", // redefine general property 'align' myCustomProperty: "foo", // custom property sorter: function(date1, date2) { return new Date(date1) - new Date(date2); }, itemTemplate: function(value) { return new Date(value).toDateString(); }, insertTemplate: function(value) { return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); }, editTemplate: function(value) { return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); }, insertValue: function() { return this._insertPicker.datepicker("getDate").toISOString(); }, editValue: function() { return this._editPicker.datepicker("getDate").toISOString(); } }); jsGrid.fields.date = MyDateField; ``` To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. Here `itemTemplate` just returns the string representation of a date. `insertTemplate` and `editTemplate` create jQuery UI datePicker for inserting and editing row. Of course jquery ui library should be included to make it work. `insertValue` and `editValue` return date to insert and update items accordingly. We also defined date specific sorter. Now, our new field `date` can be used in the grid config as follows: ```javascript { fields: [ ... { type: "date", myCustomProperty: "bar" }, ... ] } ``` ## Methods jsGrid methods could be called with `jsGrid` jQuery plugin or directly. To use jsGrid plugin to call a method, just call `jsGrid` with method name and required parameters as next arguments: ```javascript // calling method with jQuery plugin $("#grid").jsGrid("methodName", param1, param2); ``` To call method directly you need to retrieve grid instance or just create grid with the constructor: ```javascript // retrieve grid instance from element data var grid = $("#grid").data("JSGrid"); // create grid with the constructor var grid = new jsGrid.Grid($("#grid"), { ... }); // call method directly grid.methodName(param1, param2); ``` ### cancelEdit() Cancels row editing. ```javascript $("#grid").jsGrid("cancelEdit"); ``` ### clearFilter(): `Promise` Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed. ```javascript $("#grid").jsGrid("clearFilter").done(function() { console.log("filtering completed"); }); ``` ### clearInsert() Clears current inserting row. ```javascript $("#grid").jsGrid("clearInsert"); ``` ### deleteItem(item|$row|rowNode): `Promise` Removes specified row from the grid. Returns jQuery promise resolved when deletion is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // delete row by item reference $("#grid").jsGrid("deleteItem", item); // delete row by jQueryElement $("#grid").jsGrid("deleteItem", $(".specific-row")); // delete row by DomNode $("#grid").jsGrid("deleteItem", rowNode); ``` ### destroy() Destroys the grid and brings the Node to its original state. ```javascript $("#grid").jsGrid("destroy"); ``` ### editItem(item|$row|rowNode) Sets grid editing row. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // edit row by item reference $("#grid").jsGrid("editItem", item); // edit row by jQueryElement $("#grid").jsGrid("editItem", $(".specific-row")); // edit row by DomNode $("#grid").jsGrid("editItem", rowNode); ``` ### getFilter(): `Object` Get grid filter as a plain object. ```javascript var filter = $("#grid").jsGrid("getFilter"); ``` ### getSorting(): `Object` > version added: 1.2 Get grid current sorting params as a plain object with the following format: ```javascript { field, // the name of the field by which grid is sorted order // 'asc' or 'desc' depending on sort order } ``` ```javascript var sorting = $("#grid").jsGrid("getSorting"); ``` ### fieldOption(fieldName|fieldIndex, optionName, [optionValue]) > version added: 1.3 Gets or sets the value of a field option. **fieldName|fieldIndex** is the name or the index of the field to get/set the option value (if the grid contains more than one field with the same name, the first field will be used). **optionName** is the name of the field option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the field option `optionName` will be returned. ```javascript // hide the field "ClientName" $("#grid").jsGrid("fieldOption", "ClientName", "visible", false); // get width of the 2nd field var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width"); ``` ### insertItem([item]): `Promise` Inserts row into the grid based on item. Returns jQuery promise resolved when insertion is completed. **item** is the item to pass to `controller.insertItem`. If `item` is not specified the data from inserting row will be inserted. ```javascript // insert item from inserting row $("#grid").jsGrid("insertItem"); // insert item $("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() { console.log("insertion completed"); }); ``` ### loadData([filter]): `Promise` Loads data calling corresponding `controller.loadData` method. Returns jQuery promise resolved when data loading is completed. It preserves current sorting and paging unlike the `search` method . **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // load data with current grid filter $("#grid").jsGrid("loadData"); // loadData with custom filter $("#grid").jsGrid("loadData", { Name: "John" }).done(function() { console.log("data loaded"); }); ``` ### exportData([options]) Transforms the grid data into the specified output type. Output can be formatted, filtered or modified by providing options. Currently only supports CSV output. ```javascript //Basic export var csv = $("#grid").jsGrid("exportData"); //Full Options var csv = $("#grid").jsGrid("exportData", { type: "csv", //Only CSV supported subset: "all" | "visible", //Visible will only output the currently displayed page delimiter: "|", //If using csv, the character to seperate fields includeHeaders: true, //Include header row in output encapsulate: true, //Surround each field with qoutation marks; needed for some systems newline: "\r\n", //Newline character to use //Takes each item and returns true if it should be included in output. //Executed only on the records within the given subset above. filter: function(item){return true}, //Transformations are a way to modify the display value of the output. //Provide a key of the field name, and a function that takes the current value. transformations: { "Married": function(value){ if (value === true){ return "Yes" } else{ return "No" } } } }); ``` ### openPage(pageIndex) Opens the page of specified index. **pageIndex** is one-based index of the page to open. The value should be in range from 1 to [total amount of pages]. ### option(optionName, [optionValue]) Gets or sets the value of an option. **optionName** is the name of the option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the option `optionName` will be returned. ```javascript // turn off paging $("#grid").jsGrid("option", "paging", false); // get current page index var pageIndex = $("#grid").jsGrid("option", "pageIndex"); ``` ### refresh() Refreshes the grid. Renders the grid body and pager content, recalculates sizes. ```javascript $("#grid").jsGrid("refresh"); ``` ### render(): `Promise` Performs complete grid rendering. If option `autoload` is `true` calls `controller.loadData`. The state of the grid like current page and sorting is retained. Returns jQuery promise resolved when data loading is completed. If auto-loading is disabled the promise is instantly resolved. ```javascript $("#grid").jsGrid("render").done(function() { console.log("rendering completed and data loaded"); }); ``` ### reset() Resets the state of the grid. Goes to the first data page, resets sorting, and then calls `refresh`. ```javascript $("#grid").jsGrid("reset"); ``` ### rowByItem(item): `jQueryElement` > version added: 1.3 Gets the row jQuery element corresponding to the item. **item** is the item corresponding to the row. ```javascript var $row = $("#grid").jsGrid("rowByItem", item); ``` ### search([filter]): `Promise` Performs filtering of the grid. Returns jQuery promise resolved when data loading is completed. It resets current sorting and paging unlike the `loadData` method. **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // search with current grid filter $("#grid").jsGrid("search"); // search with custom filter $("#grid").jsGrid("search", { Name: "John" }).done(function() { console.log("filtering completed"); }); ``` ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showPrevPages"); ``` ### showNextPages() Shows next set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ``` ## Callbacks jsGrid allows to specify a callback function to be executed on a particular event. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid onError: function(args) {}, // on fail of any controller call onOptionChanging: function(args) {}, // before changing the grid option onOptionChanged: function(args) {}, // after changing the grid option onPageChanged: function(args) {}, // after changing the current page onRefreshing: function(args) {}, // before grid refresh onRefreshed: function(args) {}, // after grid refresh } ``` ### onDataLoading Fires before data loading. Has the following arguments: ```javascript { grid // grid instance filter // loading filter object } ``` #### Cancel Data Loading > version added: 1.2 To cancel data loading set `args.cancel = true`. In the following example loading is canceled when the filter has empty 'name' field: ```javascript $("#grid").jsGrid({ ... onDataLoading: function(args) { // cancel loading data if 'name' is empty if(args.filter.name === "") { args.cancel = true; } } }); ``` ### onDataLoaded Fires after data loading. Has the following arguments: ```javascript { grid // grid instance data // load result (array of items or data structure for loading by page scenario) } ``` In the following example the loaded data is written to the browser console. ```javascript $("#grid").jsGrid({ ... onDataLoaded: function(args) { console.log(args.data); } }); ``` ### onInit > version added: 1.5 Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a string regexp in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The
1
Clarify use of regexp for pattern validator
1
.md
md
mit
tabalinas/jsgrid
10062906
<NME> RouteRegistrar.php <BEF> <?php namespace Dusterio\LumenPassport; class RouteRegistrar { /** * @var Application */ private $app; /** * @var array */ private $options; /** * Create a new route registrar instance. * * @param $app * @param array $options */ public function __construct($app, array $options = []) { $this->app = $app; $this->options = $options; } /** * Register routes for transient tokens, clients, and personal access tokens. * * @return void */ public function all() { $this->forAccessTokens(); $this->forTransientTokens(); $this->forClients(); $this->forPersonalAccessTokens(); } /** * @param string $path * @return string */ private function prefix($path) { if (strstr($path, '\\') === false && isset($this->options['namespace'])) { return $this->options['namespace'] . '\\' . $path; } return $path; } /** * Register the routes for retrieving and issuing access tokens. * * @return void */ public function forAccessTokens() { $this->app->post('/token', $this->prefix('\Dusterio\LumenPassport\Http\Controllers\AccessTokenController@issueToken')); $this->app->group(['middleware' => ['auth']], function () { $this->app->get('/tokens', $this->prefix('AuthorizedAccessTokenController@forUser')); $this->app->delete('/tokens/{token_id}', $this->prefix('AuthorizedAccessTokenController@destroy')); }); } /** * Register the routes needed for refreshing transient tokens. * * @return void */ public function forTransientTokens() { $this->app->post('/token/refresh', [ 'middleware' => ['auth'], 'uses' => $this->prefix('TransientTokenController@refresh') ]); } /** * Register the routes needed for managing clients. * * @return void */ public function forClients() { $this->app->group(['middleware' => ['auth']], function () { $this->app->get('/clients', $this->prefix('ClientController@forUser')); $this->app->post('/clients', $this->prefix('ClientController@store')); $this->app->put('/clients/{client_id}', $this->prefix('ClientController@update')); $this->app->delete('/clients/{client_id}', $this->prefix('ClientController@destroy')); }); } /** * Register the routes needed for managing personal access tokens. * * @return void */ public function forPersonalAccessTokens() { $this->app->group(['middleware' => ['auth']], function () { $this->app->get('/scopes', $this->prefix('ScopeController@all')); $this->app->get('/personal-access-tokens', $this->prefix('PersonalAccessTokenController@forUser')); $this->app->post('/personal-access-tokens', $this->prefix('PersonalAccessTokenController@store')); $this->app->delete('/personal-access-tokens/{tokenId}', $this->prefix('PersonalAccessTokenController@destroy')); }); } } <MSG> Merge pull request #156 from santilorenzo/master Fix #154 - add compatibility to Passport 10.x <DFF> @@ -63,7 +63,7 @@ class RouteRegistrar $this->app->group(['middleware' => ['auth']], function () { $this->app->get('/tokens', $this->prefix('AuthorizedAccessTokenController@forUser')); - $this->app->delete('/tokens/{token_id}', $this->prefix('AuthorizedAccessTokenController@destroy')); + $this->app->delete('/tokens/{tokenId}', $this->prefix('AuthorizedAccessTokenController@destroy')); }); } @@ -90,8 +90,8 @@ class RouteRegistrar $this->app->group(['middleware' => ['auth']], function () { $this->app->get('/clients', $this->prefix('ClientController@forUser')); $this->app->post('/clients', $this->prefix('ClientController@store')); - $this->app->put('/clients/{client_id}', $this->prefix('ClientController@update')); - $this->app->delete('/clients/{client_id}', $this->prefix('ClientController@destroy')); + $this->app->put('/clients/{clientId}', $this->prefix('ClientController@update')); + $this->app->delete('/clients/{clientId}', $this->prefix('ClientController@destroy')); }); }
3
Merge pull request #156 from santilorenzo/master
3
.php
php
mit
dusterio/lumen-passport
10062907
<NME> module.render.js <BEF> describe('View#render()', function() { var viewToTest; beforeEach(function() { viewToTest = helpers.createView(); }); test("The master view should have an element post render.", function() { viewToTest.render(); expect(viewToTest.el).toBeDefined(); }); test("before render and render events should be fired", function() { var beforeRenderSpy = jest.fn(); var renderSpy = jest.fn(); viewToTest.on('before render', beforeRenderSpy); viewToTest.on('render', renderSpy); viewToTest.render(); expect(beforeRenderSpy.mock.invocationCallOrder[0]).toBeLessThan(renderSpy.mock.invocationCallOrder[0]); }); test("Data should be present in the generated markup.", function() { var text = 'some orange text'; var orange = new Orange({ model: { text: text } }); orange .render() .inject(sandbox); expect(orange.el.innerHTML).toEqual(text); }); test("Should be able to use Backbone models", function() { var orange = new Orange({ model: { text: 'orange text' } }); orange.render(); expect(orange.el.innerHTML).toEqual('orange text'); }); test("Child html should be present in the parent.", function() { var layout = new Layout(); var apple = new Apple(); layout .add(apple, 1) .render(); firstChild = layout.el.firstElementChild; expect(firstChild.classList.contains('apple')).toBe(true); }); test("Should be of the tag specified", function() { var apple = new Apple({ tag: 'ul' }); apple.render(); expect('UL').toEqual(apple.el.tagName); }); test("Should have classes on the element", function() { var apple = new Apple({ classes: ['foo', 'bar'] }); apple.render(); expect('apple foo bar').toEqual(apple.el.className); }); test("Should have an id attribute with the value of `fmid`", function() { var apple = new Apple({ classes: ['foo', 'bar'] }); apple.render(); expect(apple._fmid).toEqual(apple.el.id); }); test("Should have populated all child module.el properties", function() { var layout = new Layout({ children: { 1: { module: 'apple', children: { 1: { module: 'apple', children: { 1: { module: 'apple' } } } } } } }); var apple1 = layout.module('apple'); var apple2 = apple1.module('apple'); var apple3 = apple2.module('apple'); layout.render(); expect(apple1.el).toBeTruthy(); expect(apple2.el).toBeTruthy(); expect(apple3.el).toBeTruthy(); }); test("The outer DOM node should be recycled between #renders", function() { var layout = new Layout({ children: { 1: { module: 'apple' } } }); layout.render(); layout.el.setAttribute('data-test', 'should-not-be-blown-away'); layout.module('apple').el.setAttribute('data-test', 'should-be-blown-away'); layout.render(); // The DOM node of the FM module that render is called on should be recycled expect(layout.el.getAttribute('data-test')).toEqual('should-not-be-blown-away'); assert.equals(layout.el.className, 'layout should-persist'); }, "tearDown": helpers.destroyView }); viewToTest.module('apple').on('unmount', appleSpy); viewToTest.module('orange').on('unmount', orangeSpy); viewToTest.module('pear').on('unmount', pearSpy); viewToTest.render(); expect(appleSpy).not.toHaveBeenCalled(); expect(orangeSpy).not.toHaveBeenCalled(); expect(pearSpy).not.toHaveBeenCalled(); viewToTest.render(); expect(appleSpy).toHaveBeenCalled(); expect(orangeSpy).toHaveBeenCalled(); expect(pearSpy).toHaveBeenCalled(); }); afterEach(function() { helpers.destroyView(); viewToTest = null; }); }); <MSG> Merge pull request #88 from quarterto/mount-lifecycle-event Add mount lifecycle method/event and unmount event <DFF> @@ -132,5 +132,25 @@ buster.testCase('View#render()', { assert.equals(layout.el.className, 'layout should-persist'); }, + "Should fire unmount on children when rerendering": function() { + var appleSpy = this.spy(); + var orangeSpy = this.spy(); + var pearSpy = this.spy(); + + this.view.module('apple').on('unmount', appleSpy); + this.view.module('orange').on('unmount', orangeSpy); + this.view.module('pear').on('unmount', pearSpy); + + this.view.render(); + refute.called(appleSpy); + refute.called(orangeSpy); + refute.called(pearSpy); + + this.view.render(); + assert.called(appleSpy); + assert.called(orangeSpy); + assert.called(pearSpy); + }, + "tearDown": helpers.destroyView });
20
Merge pull request #88 from quarterto/mount-lifecycle-event
0
.js
render
mit
ftlabs/fruitmachine
10062908
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062909
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062910
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062911
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062912
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062913
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062914
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062915
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062916
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062917
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062918
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062919
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062920
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062921
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062922
<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 { _toolTipContent.Content = description; } _toolTip.IsOpen = false; //Popup needs to be closed to change position //Calculate offset for tooltip if (CompletionList.CurrentList != null) { int index = CompletionList.CurrentList.IndexOf(item); int scrollIndex = (int)CompletionList.ListBox.Scroll.Offset.Y; int yoffset = index - scrollIndex; if (yoffset < 0) yoffset = 0; if ((yoffset+1) * 20 > MaxHeight) yoffset--; _toolTip.Offset = new PixelPoint(2, yoffset * 20); //Todo find way to measure item height } _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; if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); } } } } 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> Fix showing empty completionwindow <DFF> @@ -225,6 +225,9 @@ namespace AvaloniaEdit.CodeCompletion if (document != null) { CompletionList.SelectItem(document.GetText(StartOffset, offset - StartOffset)); + + if (CompletionList.ListBox.ItemCount == 0) IsVisible = false; + else IsVisible = true; } } }
3
Fix showing empty completionwindow
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062923
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062924
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062925
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062926
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062927
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062928
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062929
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062930
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062931
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062932
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062933
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062934
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062935
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062936
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062937
<NME> ChangeDocumentTests.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.Text; using AvaloniaEdit.AvaloniaMocks; using AvaloniaEdit.Document; using NUnit.Framework; namespace AvaloniaEdit.Editing { [TestFixture] public class ChangeDocumentTests { [Test] public void ClearCaretAndSelectionOnDocumentChange() { using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = new TextDocument("1\n2nd"); Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] public void SetDocumentToNull() using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); textArea.Caret.Offset = 6; textArea.Selection = Selection.Create(textArea, 3, 6); textArea.Document = null; Assert.AreEqual(0, textArea.Caret.Offset); Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location); Assert.IsTrue(textArea.Selection.IsEmpty); } } [Test] using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument(); StringBuilder b = new StringBuilder(); textArea.TextView.DocumentChanged += delegate { b.Append("TextView.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.DocumentChanged += delegate { b.Append("TextArea.DocumentChanged;"); Assert.AreSame(newDocument, textArea.TextView.Document); Assert.AreSame(newDocument, textArea.Document); }; textArea.Document = newDocument; Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString()); } } } } <MSG> Merge pull request #165 from AvaloniaUI/fix-empty-lines-height Fixed empty lines height <DFF> @@ -32,7 +32,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -51,7 +52,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); textArea.Document = new TextDocument("1\n2\n3\n4th line"); @@ -70,7 +72,8 @@ namespace AvaloniaEdit.Editing using (UnitTestApplication.Start(new TestServices( renderInterface: new MockPlatformRenderInterface(), platform: new MockRuntimePlatform(), - platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration()))) + platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(), + fontManagerImpl: new MockFontManagerImpl()))) { TextArea textArea = new TextArea(); TextDocument newDocument = new TextDocument();
6
Merge pull request #165 from AvaloniaUI/fix-empty-lines-height
3
.cs
Tests/Editing/ChangeDocumentTests
mit
AvaloniaUI/AvaloniaEdit
10062938
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062939
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062940
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062941
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062942
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062943
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062944
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062945
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062946
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062947
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062948
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062949
<NME> TextEditor.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void Copy() { if (ApplicationCommands.Copy.CanExecute(null, TextArea)) { ApplicationCommands.Copy.Execute(null, TextArea); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() /// </summary> public void Cut() { if (ApplicationCommands.Cut.CanExecute(null, TextArea)) { ApplicationCommands.Cut.Execute(null, TextArea); } public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { /// </summary> public void Delete() { if(ApplicationCommands.Delete.CanExecute(null, TextArea)) { ApplicationCommands.Delete.Execute(null, TextArea); } /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> /// </summary> public void Paste() { if (ApplicationCommands.Paste.CanExecute(null, TextArea)) { ApplicationCommands.Paste.Execute(null, TextArea); } /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { /// </summary> public void SelectAll() { if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) { ApplicationCommands.SelectAll.Execute(null, TextArea); } /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets the vertical size of the document. /// </summary> /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #236 from AvaloniaUI/context-menu-automation Expose properties for context menus <DFF> @@ -587,7 +587,7 @@ namespace AvaloniaEdit /// </summary> public void Copy() { - if (ApplicationCommands.Copy.CanExecute(null, TextArea)) + if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } @@ -598,7 +598,7 @@ namespace AvaloniaEdit /// </summary> public void Cut() { - if (ApplicationCommands.Cut.CanExecute(null, TextArea)) + if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } @@ -618,7 +618,7 @@ namespace AvaloniaEdit /// </summary> public void Delete() { - if(ApplicationCommands.Delete.CanExecute(null, TextArea)) + if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } @@ -709,7 +709,7 @@ namespace AvaloniaEdit /// </summary> public void Paste() { - if (ApplicationCommands.Paste.CanExecute(null, TextArea)) + if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } @@ -772,7 +772,7 @@ namespace AvaloniaEdit /// </summary> public void SelectAll() { - if (ApplicationCommands.SelectAll.CanExecute(null, TextArea)) + if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } @@ -808,6 +808,54 @@ namespace AvaloniaEdit get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } + /// <summary> + /// Gets if text in editor can be copied + /// </summary> + public bool CanCopy + { + get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be cut + /// </summary> + public bool CanCut + { + get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text in editor can be pasted + /// </summary> + public bool CanPaste + { + get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if selected text in editor can be deleted + /// </summary> + public bool CanDelete + { + get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text the editor can select all + /// </summary> + public bool CanSelectAll + { + get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } + } + + /// <summary> + /// Gets if text editor can activate the search panel + /// </summary> + public bool CanSearch + { + get { return searchPanel != null; } + } + /// <summary> /// Gets the vertical size of the document. /// </summary>
53
Merge pull request #236 from AvaloniaUI/context-menu-automation
5
.cs
cs
mit
AvaloniaUI/AvaloniaEdit