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
10062750
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); } fm.create = module.exports; fm.Model = options.Model; fm.Events = events; fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; } }, fmid: function() { return this._fmid; }, toHTML: function() { var data = {}; var children = this.children(); }, wrapHTML: function(html) { return '<' + this.tag + ' class="' + this.module + ' ' + this.classes.join(' ') + '" id="' + this.fmid() + '">' + html + '</div>'; }, purgeHtmlCache: function() { el: function() { if (!hasDom) return; return this._el = this._el || document.getElementById(this.fmid()) || this.parent && util.querySelectorId(this.fmid(), this.closestElement()); }, setElement: function(el) { } json.id = this.id(); json.fmid = this.fmid(); json.module = this.module; json.data = this.model.get(); return json; <MSG> Depricated View#fmid() in favour of view._fmid for internal use only <DFF> @@ -479,10 +479,6 @@ } }, - fmid: function() { - return this._fmid; - }, - toHTML: function() { var data = {}; var children = this.children(); @@ -505,7 +501,7 @@ }, wrapHTML: function(html) { - return '<' + this.tag + ' class="' + this.module + ' ' + this.classes.join(' ') + '" id="' + this.fmid() + '">' + html + '</div>'; + return '<' + this.tag + ' class="' + this.module + ' ' + this.classes.join(' ') + '" id="' + this._fmid + '">' + html + '</div>'; }, purgeHtmlCache: function() { @@ -670,8 +666,8 @@ el: function() { if (!hasDom) return; return this._el = this._el - || document.getElementById(this.fmid()) - || this.parent && util.querySelectorId(this.fmid(), this.closestElement()); + || document.getElementById(this._fmid) + || this.parent && util.querySelectorId(this._fmid, this.closestElement()); }, setElement: function(el) { @@ -792,7 +788,7 @@ } json.id = this.id(); - json.fmid = this.fmid(); + json.fmid = this._fmid; json.module = this.module; json.data = this.model.get(); return json;
4
Depricated View#fmid() in favour of view._fmid for internal use only
8
.js
js
mit
ftlabs/fruitmachine
10062751
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062752
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062753
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062754
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062755
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062756
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062757
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062758
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062759
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062760
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062761
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062762
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062763
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062764
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062765
<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 readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlBtn; private Button _clearControlBtn; private Button _changeThemeBtn; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); 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.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlBtn = this.FindControl<Button>("addControlBtn"); _addControlBtn.Click += _addControlBtn_Click; _clearControlBtn = this.FindControl<Button>("clearControlBtn"); _clearControlBtn.Click += _clearControlBtn_Click; ; _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); _changeThemeBtn.Click += _changeThemeBtn_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); 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) private void Caret_PositionChanged(object sender, EventArgs e) { _textMateInstallation.Dispose(); } private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; base.OnClosed(e); _textMateInstallation.Dispose(); _textMateInstallation.SetGrammar(scopeName); } void _changeThemeBtn_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); { AvaloniaXamlLoader.Load(this); } void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { { 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; // We still want to insert the character that was typed. } void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { 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"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { 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> Tidy MainWindow.xaml.cs <DFF> @@ -28,9 +28,9 @@ namespace AvaloniaEdit.Demo private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; - private Button _addControlBtn; - private Button _clearControlBtn; - private Button _changeThemeBtn; + private Button _addControlButton; + private Button _clearControlButton; + private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); @@ -60,14 +60,14 @@ namespace AvaloniaEdit.Demo _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; - _addControlBtn = this.FindControl<Button>("addControlBtn"); - _addControlBtn.Click += _addControlBtn_Click; + _addControlButton = this.FindControl<Button>("addControlBtn"); + _addControlButton.Click += AddControlButton_Click; - _clearControlBtn = this.FindControl<Button>("clearControlBtn"); - _clearControlBtn.Click += _clearControlBtn_Click; ; + _clearControlButton = this.FindControl<Button>("clearControlBtn"); + _clearControlButton.Click += ClearControlButton_Click; ; - _changeThemeBtn = this.FindControl<Button>("changeThemeBtn"); - _changeThemeBtn.Click += _changeThemeBtn_Click; + _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); + _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); @@ -81,7 +81,7 @@ namespace AvaloniaEdit.Demo _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; - _syntaxModeCombo.SelectionChanged += _syntaxModeCombo_SelectionChanged; + _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); @@ -100,7 +100,9 @@ namespace AvaloniaEdit.Demo private void Caret_PositionChanged(object sender, EventArgs e) { - _statusTextBlock.Text = String.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); + _statusTextBlock.Text = string.Format("Line {0} Column {1}", + _textEditor.TextArea.Caret.Line, + _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) @@ -110,7 +112,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.Dispose(); } - private void _syntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) + private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { Language language = (Language)_syntaxModeCombo.SelectedItem; @@ -120,7 +122,7 @@ namespace AvaloniaEdit.Demo _textMateInstallation.SetGrammar(scopeName); } - void _changeThemeBtn_Click(object sender, RoutedEventArgs e) + private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; @@ -132,21 +134,21 @@ namespace AvaloniaEdit.Demo { AvaloniaXamlLoader.Load(this); } - - void _addControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + + private void AddControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } - void _clearControlBtn_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) + private void ClearControlButton_Click(object sender, Avalonia.Interactivity.RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } - void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { @@ -164,7 +166,7 @@ namespace AvaloniaEdit.Demo // We still want to insert the character that was typed. } - void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) + private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") {
20
Tidy MainWindow.xaml.cs
18
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10062766
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062767
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062768
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062769
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062770
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062771
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062772
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062773
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062774
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062775
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062776
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062777
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062778
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062779
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062780
<NME> OverloadInsightWindow.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using AvaloniaEdit.Editing; using Avalonia.Input; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Insight window that shows an OverloadViewer. /// </summary> public class OverloadInsightWindow : InsightWindow { private readonly OverloadViewer _overloadViewer = new OverloadViewer(); /// <summary> /// Creates a new OverloadInsightWindow. /// </summary> public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); Content = _overloadViewer; } /// <summary> /// Gets/Sets the item provider. /// </summary> public IOverloadProvider Provider { get => _overloadViewer.Provider; set => _overloadViewer.Provider = value; } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && Provider != null && Provider.Count > 1) { switch (e.Key) { case Key.Up: e.Handled = true; _overloadViewer.ChangeIndex(-1); break; case Key.Down: e.Handled = true; _overloadViewer.ChangeIndex(+1); break; } if (e.Handled) { // TODO: UpdateLayout(); UpdatePosition(); } } } } } <MSG> Use Popup instead of PopupRoot <DFF> @@ -35,7 +35,7 @@ namespace AvaloniaEdit.CodeCompletion public OverloadInsightWindow(TextArea textArea) : base(textArea) { _overloadViewer.Margin = new Thickness(2, 0, 0, 0); - Content = _overloadViewer; + Child = _overloadViewer; } /// <summary>
1
Use Popup instead of PopupRoot
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062781
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062782
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062783
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062784
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062785
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062786
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062787
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062788
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062789
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062790
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062791
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062792
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062793
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062794
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062795
<NME> InsightWindow.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.Controls.Platform; using AvaloniaEdit.Editing; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// A popup-like window that is attached to a text segment. /// </summary> public class InsightWindow : CompletionWindowBase { /// <summary> /// Creates a new InsightWindow. /// </summary> public InsightWindow(TextArea textArea) : base(textArea) { CloseAutomatically = true; AttachEvents(); Initialize(); PlacementTarget = textArea; PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize() { // TODO: working area //var caret = this.TextArea.Caret.CalculateCaretRectangle(); //var pointOnScreen = this.TextArea.TextView.PointToScreen(caret.Location - this.TextArea.TextView.ScrollOffset); //Rect workingArea = System.Windows.Forms.Screen.FromPoint(pointOnScreen.ToSystemDrawing()).WorkingArea.ToWpf().TransformFromDevice(this); //MaxHeight = workingArea.Height; //MaxWidth = Math.Min(workingArea.Width, Math.Max(1000, workingArea.Width * 0.6)); } /// <summary> /// Gets/Sets whether the insight window should close automatically. /// The default value is true. /// </summary> public bool CloseAutomatically { get; set; } /// <inheritdoc/> protected override bool CloseOnFocusLost => CloseAutomatically; private void AttachEvents() { TextArea.Caret.PositionChanged += CaretPositionChanged; } /// <inheritdoc/> protected override void DetachEvents() { TextArea.Caret.PositionChanged -= CaretPositionChanged; base.DetachEvents(); } private void CaretPositionChanged(object sender, EventArgs e) { if (CloseAutomatically) { var offset = TextArea.Caret.Offset; if (offset < StartOffset || offset > EndOffset) { Hide(); } } } } } <MSG> Use popup instead of popuproot II <DFF> @@ -35,9 +35,6 @@ namespace AvaloniaEdit.CodeCompletion CloseAutomatically = true; AttachEvents(); Initialize(); - - PlacementTarget = textArea; - PlacementMode = Avalonia.Controls.PlacementMode.AnchorAndGravity; } private void Initialize()
0
Use popup instead of popuproot II
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062796
<NME> tests.js <BEF> /** * loadjs tests * @module test/tests.js */ var pathsLoaded = null, // file register testEl = null, assert = chai.assert, expect = chai.expect; describe('LoadJS tests', function() { beforeEach(function() { // reset register pathsLoaded = {}; // reset loadjs dependencies loadjs.reset(); }); // ========================================================================== // JavaScript file loading tests // ========================================================================== describe('JavaScript file loading tests', function() { it('should call success callback on valid path', function(done) { loadjs(['assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); done(); } }); }); it('should call error callback on invalid path', function(done) { loadjs(['assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should call before callback before embedding into document', function(done) { var scriptTags = []; loadjs(['assets/file1.js', 'assets/file2.js'], { before: function(path, el) { scriptTags.push({ path: path, el: el }); // add cross origin script for file2 if (path === 'assets/file2.js') { el.crossOrigin = 'anonymous'; } }, success: function() { assert.equal(scriptTags[0].path, 'assets/file1.js'); assert.equal(scriptTags[1].path, 'assets/file2.js'); assert.equal(scriptTags[0].el.crossOrigin, undefined); assert.equal(scriptTags[1].el.crossOrigin, 'anonymous'); done(); } }); }); it('should bypass insertion if before returns `false`', function(done) { loadjs(['assets/file1.js'], { before: function(path, el) { // append to body (instead of head) document.body.appendChild(el); // return `false` to bypass default DOM insertion return false; }, success: function() { assert.equal(pathsLoaded['file1.js'], true); // verify that file was added to body var els = document.body.querySelectorAll('script'), el; for (var i=0; i < els.length; i++) { el = els[i]; if (el.src.indexOf('assets/file1.js') !== -1) done(); } } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should support async false', function(done) { this.timeout(5000); var numCompleted = 0, numTests = 20, paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js']; // run tests sequentially var testFn = function(paths) { // add cache busters var pathsUncached = paths.slice(0); pathsUncached[0] += '?_=' + Math.random(); pathsUncached[1] += '?_=' + Math.random(); loadjs(pathsUncached, { success: function() { var f1 = paths[0].replace('assets/', ''); var f2 = paths[1].replace('assets/', ''); // check load order assert.isTrue(pathsLoaded[f1]); assert.isFalse(pathsLoaded[f2]); // increment tests numCompleted += 1; if (numCompleted === numTests) { // exit done(); } else { // reset register pathsLoaded = {}; // run test again paths.reverse(); testFn(paths); } }, async: false }); }; // run tests testFn(paths); }); it('should support multiple tries', function(done) { loadjs('assets/file-numretries.js', { error: function() { // check number of scripts in document var selector = 'script[src="assets/file-numretries.js"]', scripts = document.querySelectorAll(selector); if (scripts.length === 2) done(); }, numRetries: 1 }); }); // Un-'x' this for testing ad blocked scripts. // Ghostery: Disallow "Google Adservices" // AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a // custom filter under Options // xit('it should report ad blocked scripts as missing', function(done) { var s1 = 'https://www.googletagservices.com/tag/js/gpt.js', s2 = 'https://munchkin.marketo.net/munchkin-beta.js'; loadjs([s1, s2, 'assets/file1.js'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 2); assert.equal(pathsNotFound[0], s1); assert.equal(pathsNotFound[1], s2); done(); } }); }); }); // ========================================================================== // CSS file loading tests // ========================================================================== describe('CSS file loading tests', function() { before(function() { // add test div to body for css tests testEl = document.createElement('div'); testEl.className = 'test-div mui-container'; testEl.style.display = 'inline-block'; document.body.appendChild(testEl); }); afterEach(function() { var els = document.getElementsByTagName('link'), i = els.length, el; // iteratete through stylesheets while (i--) { el = els[i]; // remove test stylesheets if (el.href.indexOf('mocha.css') === -1) { el.parentNode.removeChild(el); } } }); it('should load one file', function(done) { loadjs(['assets/file1.css'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/file1.css', 'assets/file2.css'], { success: function() { assert.equal(testEl.offsetWidth, 200); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(testEl.offsetWidth, 100); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css'); done(); } }); }); it('should support mix of css and js', function(done) { loadjs(['assets/file1.css', 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should support forced "css!" files', function(done) { //this.timeout(0); loadjs(['css!assets/file1.css'], { success: function() { // loop through files var els = document.getElementsByTagName('link'), i = els.length, el; while (i--) { if (els[i].href.indexOf('file1.css') !== -1) done(); } } }); }); it('supports urls with query arguments', function(done) { loadjs(['assets/file1.css?x=x'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with anchor tags', function(done) { loadjs(['assets/file1.css#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { loadjs(['assets/file1.css?x=x#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load external css files', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], { success: function() { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '15px'); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '0px'); assert.equal(pathsNotFound.length, 1); done(); } }); }); // teardown return after(function() { // remove test div testEl.parentNode.removeChild(testEl); }); }); // ========================================================================== // Image file loading tests // ========================================================================== describe('Image file loading tests', function() { function assertLoaded(src) { var i = new Image(); i.src = src; assert.equal(i.naturalWidth > 0, true); } function assertNotLoaded(src) { var i = new Image(); i.src = src; assert.equal(i.naturalWidth, 0) } it('should load one file', function(done) { loadjs(['assets/flash.png'], { success: function() { assertLoaded('assets/flash.png'); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/flash.png', 'assets/flash.jpg'], { success: function() { assertLoaded('assets/flash.png'); assertLoaded('assets/flash.jpg'); done(); } }); }); it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); var src = 'assets/flash.png'; src += '?' + Math.random(); src += '#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error callback on one invalid path', function(done) { var src1 = 'assets/flash.png?' + Math.random(), src2 = 'assets/flash-doesntexist.png?' + Math.random(); loadjs(['img!' + src1, 'img!' + src2], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assertLoaded(src1); assertNotLoaded(src2); done(); } }); }); var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); assertLoaded(src); done(); } }); }); it('should load external img files', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/'; src += 'mui-logo-doesntexist.png?' + Math.random(); loadjs(['img!' + src], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assertNotLoaded(src); done(); } }); }); }); // ========================================================================== // API tests // ========================================================================== describe('API tests', function() { it('should throw an error if bundle is already defined', function() { // define bundle loadjs(['assets/file1.js'], 'bundle'); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'bundle'); }; expect(fn).to.throw("LoadJS"); }); it('should create a bundle id and a callback inline', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should chain loadjs object', function(done) { function bothDone() { if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done(); } // define bundles loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs .ready('bundle1', { success: function() { assert.equal(pathsLoaded['file1.js'], true); bothDone(); }}) .ready('bundle2', { success: function() { assert.equal(pathsLoaded['file2.js'], true); bothDone(); } }); }); it('should handle multiple dependencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should error on missing depdendencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file-doesntexist.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { throw "Executed success callback"; }, error: function(depsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(depsNotFound.length, 1); assert.equal(depsNotFound[0], 'bundle2'); done(); } }); }); it('should execute callbacks on .done()', function(done) { // add handler loadjs.ready('plugin', { success: function() { done(); } }); // execute done loadjs.done('plugin'); }); it('should execute callbacks created after .done()', function(done) { // execute done loadjs.done('plugin'); // add handler loadjs.ready('plugin', { success: function() { done(); } }); }); it('should define bundles', function(done) { // define bundle loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); // use 1 second delay to let files load setTimeout(function() { loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }, 1000); }); it('should allow bundle callbacks before definitions', function(done) { // define callback loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); // use 1 second delay setTimeout(function() { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); }, 1000); }); it('should reset dependencies statuses', function() { loadjs(['assets/file1.js'], 'cleared'); loadjs.reset(); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'cleared'); }; expect(fn).not.to.throw("LoadJS"); }); it('should indicate if bundle has already been defined', function() { loadjs(['assets/file1/js'], 'bundle1'); assert.equal(loadjs.isDefined('bundle1'), true); assert.equal(loadjs.isDefined('bundleXX'), false); }); it('should accept success callback functions to loadjs()', function(done) { loadjs('assets/file1.js', function() { done(); }); }); it('should accept success callback functions to .ready()', function(done) { loadjs.done('plugin'); loadjs.ready('plugin', function() { done(); }); }); it('should return Promise object if returnPromise is true', function() { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); // verify that response object is a Promise assert.equal(prom instanceof Promise, true); }); it('Promise object should support resolutions', function(done) { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); prom.then(function() { assert.equal(pathsLoaded['file1.js'], true); done(); }); }); it('Promise object should support rejections', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom.then( function(){}, function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } ); }); it('Promise object should support catches', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom .catch(function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); }); }); it('supports Promises and success callbacks', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; var prom = loadjs('assets/file1.js', { success: completedFn, returnPromise: true }); prom.then(completedFn); }); it('supports Promises and bundle ready events', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; loadjs('assets/file1.js', 'bundle1', {returnPromise: true}) .then(completedFn); loadjs.ready('bundle1', completedFn); }); }); }); <MSG> added support for image and css detection on urls with query arguments and anchor tags, bumped version number <DFF> @@ -292,8 +292,6 @@ describe('LoadJS tests', function() { it('should support forced "css!" files', function(done) { - //this.timeout(0); - loadjs(['css!assets/file1.css'], { success: function() { // loop through files @@ -386,19 +384,27 @@ describe('LoadJS tests', function() { describe('Image file loading tests', function() { function assertLoaded(src) { - var i = new Image(); - i.src = src; - assert.equal(i.naturalWidth > 0, true); + // loop through images + var imgs = document.getElementsByTagName('img'); + + Array.prototype.slice.call(imgs).forEach(function(img) { + // verify image was loaded + if (img.src === src) assert.equal(img.naturalWidth > 0, true); + }); } function assertNotLoaded(src) { - var i = new Image(); - i.src = src; - assert.equal(i.naturalWidth, 0) + // loop through images + var imgs = document.getElementsByTagName('img'); + + Array.prototype.slice.call(imgs).forEach(function(img) { + // fail if image was loaded + if (img.src === src) assert.equal(img.naturalWidth, 0); + }); } - + it('should load one file', function(done) { loadjs(['assets/flash.png'], { success: function() { @@ -420,6 +426,44 @@ describe('LoadJS tests', function() { }); + it('supports urls with query arguments', function(done) { + var src = 'assets/flash.png?' + Math.random(); + + loadjs([src], { + success: function() { + assertLoaded(src); + done(); + } + }); + }); + + + it('supports urls with anchor tags', function(done) { + var src = 'assets/flash.png#' + Math.random(); + + loadjs([src], { + success: function() { + assertLoaded(src); + done(); + } + }); + }); + + + it('supports urls with query arguments and anchor tags', function(done) { + var src = 'assets/flash.png'; + src += '?' + Math.random(); + src += '#' + Math.random(); + + loadjs([src], { + success: function() { + assertLoaded(src); + done(); + } + }); + }); + + it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); @@ -468,7 +512,7 @@ describe('LoadJS tests', function() { var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); - + loadjs(['img!' + src], { success: function() { assertLoaded(src);
54
added support for image and css detection on urls with query arguments and anchor tags, bumped version number
10
.js
js
mit
muicss/loadjs
10062797
<NME> tests.js <BEF> /** * loadjs tests * @module test/tests.js */ var pathsLoaded = null, // file register testEl = null, assert = chai.assert, expect = chai.expect; describe('LoadJS tests', function() { beforeEach(function() { // reset register pathsLoaded = {}; // reset loadjs dependencies loadjs.reset(); }); // ========================================================================== // JavaScript file loading tests // ========================================================================== describe('JavaScript file loading tests', function() { it('should call success callback on valid path', function(done) { loadjs(['assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); done(); } }); }); it('should call error callback on invalid path', function(done) { loadjs(['assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should call before callback before embedding into document', function(done) { var scriptTags = []; loadjs(['assets/file1.js', 'assets/file2.js'], { before: function(path, el) { scriptTags.push({ path: path, el: el }); // add cross origin script for file2 if (path === 'assets/file2.js') { el.crossOrigin = 'anonymous'; } }, success: function() { assert.equal(scriptTags[0].path, 'assets/file1.js'); assert.equal(scriptTags[1].path, 'assets/file2.js'); assert.equal(scriptTags[0].el.crossOrigin, undefined); assert.equal(scriptTags[1].el.crossOrigin, 'anonymous'); done(); } }); }); it('should bypass insertion if before returns `false`', function(done) { loadjs(['assets/file1.js'], { before: function(path, el) { // append to body (instead of head) document.body.appendChild(el); // return `false` to bypass default DOM insertion return false; }, success: function() { assert.equal(pathsLoaded['file1.js'], true); // verify that file was added to body var els = document.body.querySelectorAll('script'), el; for (var i=0; i < els.length; i++) { el = els[i]; if (el.src.indexOf('assets/file1.js') !== -1) done(); } } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should support async false', function(done) { this.timeout(5000); var numCompleted = 0, numTests = 20, paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js']; // run tests sequentially var testFn = function(paths) { // add cache busters var pathsUncached = paths.slice(0); pathsUncached[0] += '?_=' + Math.random(); pathsUncached[1] += '?_=' + Math.random(); loadjs(pathsUncached, { success: function() { var f1 = paths[0].replace('assets/', ''); var f2 = paths[1].replace('assets/', ''); // check load order assert.isTrue(pathsLoaded[f1]); assert.isFalse(pathsLoaded[f2]); // increment tests numCompleted += 1; if (numCompleted === numTests) { // exit done(); } else { // reset register pathsLoaded = {}; // run test again paths.reverse(); testFn(paths); } }, async: false }); }; // run tests testFn(paths); }); it('should support multiple tries', function(done) { loadjs('assets/file-numretries.js', { error: function() { // check number of scripts in document var selector = 'script[src="assets/file-numretries.js"]', scripts = document.querySelectorAll(selector); if (scripts.length === 2) done(); }, numRetries: 1 }); }); // Un-'x' this for testing ad blocked scripts. // Ghostery: Disallow "Google Adservices" // AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a // custom filter under Options // xit('it should report ad blocked scripts as missing', function(done) { var s1 = 'https://www.googletagservices.com/tag/js/gpt.js', s2 = 'https://munchkin.marketo.net/munchkin-beta.js'; loadjs([s1, s2, 'assets/file1.js'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 2); assert.equal(pathsNotFound[0], s1); assert.equal(pathsNotFound[1], s2); done(); } }); }); }); // ========================================================================== // CSS file loading tests // ========================================================================== describe('CSS file loading tests', function() { before(function() { // add test div to body for css tests testEl = document.createElement('div'); testEl.className = 'test-div mui-container'; testEl.style.display = 'inline-block'; document.body.appendChild(testEl); }); afterEach(function() { var els = document.getElementsByTagName('link'), i = els.length, el; // iteratete through stylesheets while (i--) { el = els[i]; // remove test stylesheets if (el.href.indexOf('mocha.css') === -1) { el.parentNode.removeChild(el); } } }); it('should load one file', function(done) { loadjs(['assets/file1.css'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/file1.css', 'assets/file2.css'], { success: function() { assert.equal(testEl.offsetWidth, 200); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(testEl.offsetWidth, 100); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css'); done(); } }); }); it('should support mix of css and js', function(done) { loadjs(['assets/file1.css', 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should support forced "css!" files', function(done) { //this.timeout(0); loadjs(['css!assets/file1.css'], { success: function() { // loop through files var els = document.getElementsByTagName('link'), i = els.length, el; while (i--) { if (els[i].href.indexOf('file1.css') !== -1) done(); } } }); }); it('supports urls with query arguments', function(done) { loadjs(['assets/file1.css?x=x'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with anchor tags', function(done) { loadjs(['assets/file1.css#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { loadjs(['assets/file1.css?x=x#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load external css files', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], { success: function() { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '15px'); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '0px'); assert.equal(pathsNotFound.length, 1); done(); } }); }); // teardown return after(function() { // remove test div testEl.parentNode.removeChild(testEl); }); }); // ========================================================================== // Image file loading tests // ========================================================================== describe('Image file loading tests', function() { function assertLoaded(src) { var i = new Image(); i.src = src; assert.equal(i.naturalWidth > 0, true); } function assertNotLoaded(src) { var i = new Image(); i.src = src; assert.equal(i.naturalWidth, 0) } it('should load one file', function(done) { loadjs(['assets/flash.png'], { success: function() { assertLoaded('assets/flash.png'); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/flash.png', 'assets/flash.jpg'], { success: function() { assertLoaded('assets/flash.png'); assertLoaded('assets/flash.jpg'); done(); } }); }); it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); var src = 'assets/flash.png'; src += '?' + Math.random(); src += '#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error callback on one invalid path', function(done) { var src1 = 'assets/flash.png?' + Math.random(), src2 = 'assets/flash-doesntexist.png?' + Math.random(); loadjs(['img!' + src1, 'img!' + src2], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assertLoaded(src1); assertNotLoaded(src2); done(); } }); }); var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); assertLoaded(src); done(); } }); }); it('should load external img files', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/'; src += 'mui-logo-doesntexist.png?' + Math.random(); loadjs(['img!' + src], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assertNotLoaded(src); done(); } }); }); }); // ========================================================================== // API tests // ========================================================================== describe('API tests', function() { it('should throw an error if bundle is already defined', function() { // define bundle loadjs(['assets/file1.js'], 'bundle'); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'bundle'); }; expect(fn).to.throw("LoadJS"); }); it('should create a bundle id and a callback inline', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should chain loadjs object', function(done) { function bothDone() { if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done(); } // define bundles loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs .ready('bundle1', { success: function() { assert.equal(pathsLoaded['file1.js'], true); bothDone(); }}) .ready('bundle2', { success: function() { assert.equal(pathsLoaded['file2.js'], true); bothDone(); } }); }); it('should handle multiple dependencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should error on missing depdendencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file-doesntexist.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { throw "Executed success callback"; }, error: function(depsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(depsNotFound.length, 1); assert.equal(depsNotFound[0], 'bundle2'); done(); } }); }); it('should execute callbacks on .done()', function(done) { // add handler loadjs.ready('plugin', { success: function() { done(); } }); // execute done loadjs.done('plugin'); }); it('should execute callbacks created after .done()', function(done) { // execute done loadjs.done('plugin'); // add handler loadjs.ready('plugin', { success: function() { done(); } }); }); it('should define bundles', function(done) { // define bundle loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); // use 1 second delay to let files load setTimeout(function() { loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }, 1000); }); it('should allow bundle callbacks before definitions', function(done) { // define callback loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); // use 1 second delay setTimeout(function() { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); }, 1000); }); it('should reset dependencies statuses', function() { loadjs(['assets/file1.js'], 'cleared'); loadjs.reset(); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'cleared'); }; expect(fn).not.to.throw("LoadJS"); }); it('should indicate if bundle has already been defined', function() { loadjs(['assets/file1/js'], 'bundle1'); assert.equal(loadjs.isDefined('bundle1'), true); assert.equal(loadjs.isDefined('bundleXX'), false); }); it('should accept success callback functions to loadjs()', function(done) { loadjs('assets/file1.js', function() { done(); }); }); it('should accept success callback functions to .ready()', function(done) { loadjs.done('plugin'); loadjs.ready('plugin', function() { done(); }); }); it('should return Promise object if returnPromise is true', function() { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); // verify that response object is a Promise assert.equal(prom instanceof Promise, true); }); it('Promise object should support resolutions', function(done) { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); prom.then(function() { assert.equal(pathsLoaded['file1.js'], true); done(); }); }); it('Promise object should support rejections', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom.then( function(){}, function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } ); }); it('Promise object should support catches', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom .catch(function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); }); }); it('supports Promises and success callbacks', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; var prom = loadjs('assets/file1.js', { success: completedFn, returnPromise: true }); prom.then(completedFn); }); it('supports Promises and bundle ready events', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; loadjs('assets/file1.js', 'bundle1', {returnPromise: true}) .then(completedFn); loadjs.ready('bundle1', completedFn); }); }); }); <MSG> added support for image and css detection on urls with query arguments and anchor tags, bumped version number <DFF> @@ -292,8 +292,6 @@ describe('LoadJS tests', function() { it('should support forced "css!" files', function(done) { - //this.timeout(0); - loadjs(['css!assets/file1.css'], { success: function() { // loop through files @@ -386,19 +384,27 @@ describe('LoadJS tests', function() { describe('Image file loading tests', function() { function assertLoaded(src) { - var i = new Image(); - i.src = src; - assert.equal(i.naturalWidth > 0, true); + // loop through images + var imgs = document.getElementsByTagName('img'); + + Array.prototype.slice.call(imgs).forEach(function(img) { + // verify image was loaded + if (img.src === src) assert.equal(img.naturalWidth > 0, true); + }); } function assertNotLoaded(src) { - var i = new Image(); - i.src = src; - assert.equal(i.naturalWidth, 0) + // loop through images + var imgs = document.getElementsByTagName('img'); + + Array.prototype.slice.call(imgs).forEach(function(img) { + // fail if image was loaded + if (img.src === src) assert.equal(img.naturalWidth, 0); + }); } - + it('should load one file', function(done) { loadjs(['assets/flash.png'], { success: function() { @@ -420,6 +426,44 @@ describe('LoadJS tests', function() { }); + it('supports urls with query arguments', function(done) { + var src = 'assets/flash.png?' + Math.random(); + + loadjs([src], { + success: function() { + assertLoaded(src); + done(); + } + }); + }); + + + it('supports urls with anchor tags', function(done) { + var src = 'assets/flash.png#' + Math.random(); + + loadjs([src], { + success: function() { + assertLoaded(src); + done(); + } + }); + }); + + + it('supports urls with query arguments and anchor tags', function(done) { + var src = 'assets/flash.png'; + src += '?' + Math.random(); + src += '#' + Math.random(); + + loadjs([src], { + success: function() { + assertLoaded(src); + done(); + } + }); + }); + + it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); @@ -468,7 +512,7 @@ describe('LoadJS tests', function() { var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); - + loadjs(['img!' + src], { success: function() { assertLoaded(src);
54
added support for image and css detection on urls with query arguments and anchor tags, bumped version number
10
.js
js
mit
muicss/loadjs
10062798
<NME> loadjs.min.js <BEF> loadjs=function(){var l=function(){},s={},u={},f={};function o(e,n){if(e){var t=f[e];if(u[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function a(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var s,o,e=document,n=i.async,u=(i.numRetries||0)+1,f=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(s=!0,(o=e.createElement("link")).rel="stylesheet",o.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=a:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(s&&"hideFocus"in o)try{o.sheet.cssText.length||(n="e")}catch(e){18!=e.code&&(n="e")}if("e"==n&&(c+=1)<u)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==f(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in s)throw"LoadJS";s[r]=!0}function c(n,t){!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,s=c,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--c||r(o)},i=0;i<s;i++)h(e[i],t,n)}(e,function(e){a(i,e),n&&a({success:n,error:t},e),o(r,e)},i)}if(i.returnPromise)return new Promise(c);c()}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],s=e.length,o=s;for(n=function(e,n){n.length&&c.push(e),--o||t(c)};s--;)r=e[s],(i=u[r])?n(r,i):(f[r]=f[r]||[]).push(n)}(e,function(e){a(n,e)}),t},t.done=function(e){o(e,[])},t.reset=function(){s={},u={},f={}},t.isDefined=function(e){return e in s},t}(); <MSG> updated README <DFF> @@ -1,1 +1,1 @@ -loadjs=function(){var l=function(){},s={},u={},f={};function o(e,n){if(e){var t=f[e];if(u[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function a(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var s,o,e=document,n=i.async,u=(i.numRetries||0)+1,f=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(s=!0,(o=e.createElement("link")).rel="stylesheet",o.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=a:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(s&&"hideFocus"in o)try{o.sheet.cssText.length||(n="e")}catch(e){18!=e.code&&(n="e")}if("e"==n&&(c+=1)<u)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==f(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in s)throw"LoadJS";s[r]=!0}function c(n,t){!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,s=c,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--c||r(o)},i=0;i<s;i++)h(e[i],t,n)}(e,function(e){a(i,e),n&&a({success:n,error:t},e),o(r,e)},i)}if(i.returnPromise)return new Promise(c);c()}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],s=e.length,o=s;for(n=function(e,n){n.length&&c.push(e),--o||t(c)};s--;)r=e[s],(i=u[r])?n(r,i):(f[r]=f[r]||[]).push(n)}(e,function(e){a(n,e)}),t},t.done=function(e){o(e,[])},t.reset=function(){s={},u={},f={}},t.isDefined=function(e){return e in s},t}(); \ No newline at end of file +loadjs=function(){var a=function(){},c={},u={},f={};function o(e,n){if(e){var t=f[e];if(u[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function l(e,n){e.call&&(e={success:e}),n.length?(e.error||a)(n):(e.success||a)(e)}function h(t,r,s,i){var c,o,e=document,n=s.async,u=(s.numRetries||0)+1,f=s.before||a,l=t.replace(/^(css|img)!/,"");i=i||0,/(^css!|\.css$)/.test(t)?((o=e.createElement("link")).rel="stylesheet",o.href=l,(c="hideFocus"in o)&&o.relList&&(c=0,o.rel="preload",o.as="style")):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=l:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(c)try{o.sheet.cssText.length||(n="e")}catch(e){18!=e.code&&(n="e")}if("e"==n){if((i+=1)<u)return h(t,r,s,i)}else if("preload"==o.rel&&"style"==o.as)return o.rel="stylesheet";r(t,n,e.defaultPrevented)})!==f(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,s;if(n&&n.trim&&(r=n),s=(r?t:n)||{},r){if(r in c)throw"LoadJS";c[r]=!0}function i(n,t){!function(e,r,n){var t,s,i=(e=e.push?e:[e]).length,c=i,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--i||r(o)},s=0;s<c;s++)h(e[s],t,n)}(e,function(e){l(s,e),n&&l({success:n,error:t},e),o(r,e)},s)}if(s.returnPromise)return new Promise(i);i()}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,s,i=[],c=e.length,o=c;for(n=function(e,n){n.length&&i.push(e),--o||t(i)};c--;)r=e[c],(s=u[r])?n(r,s):(f[r]=f[r]||[]).push(n)}(e,function(e){l(n,e)}),t},t.done=function(e){o(e,[])},t.reset=function(){c={},u={},f={}},t.isDefined=function(e){return e in c},t}(); \ No newline at end of file
1
updated README
1
.js
min
mit
muicss/loadjs
10062799
<NME> loadjs.min.js <BEF> loadjs=function(){var l=function(){},s={},u={},f={};function o(e,n){if(e){var t=f[e];if(u[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function a(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var s,o,e=document,n=i.async,u=(i.numRetries||0)+1,f=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(s=!0,(o=e.createElement("link")).rel="stylesheet",o.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=a:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(s&&"hideFocus"in o)try{o.sheet.cssText.length||(n="e")}catch(e){18!=e.code&&(n="e")}if("e"==n&&(c+=1)<u)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==f(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in s)throw"LoadJS";s[r]=!0}function c(n,t){!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,s=c,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--c||r(o)},i=0;i<s;i++)h(e[i],t,n)}(e,function(e){a(i,e),n&&a({success:n,error:t},e),o(r,e)},i)}if(i.returnPromise)return new Promise(c);c()}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],s=e.length,o=s;for(n=function(e,n){n.length&&c.push(e),--o||t(c)};s--;)r=e[s],(i=u[r])?n(r,i):(f[r]=f[r]||[]).push(n)}(e,function(e){a(n,e)}),t},t.done=function(e){o(e,[])},t.reset=function(){s={},u={},f={}},t.isDefined=function(e){return e in s},t}(); <MSG> updated README <DFF> @@ -1,1 +1,1 @@ -loadjs=function(){var l=function(){},s={},u={},f={};function o(e,n){if(e){var t=f[e];if(u[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function a(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var s,o,e=document,n=i.async,u=(i.numRetries||0)+1,f=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(s=!0,(o=e.createElement("link")).rel="stylesheet",o.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=a:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(s&&"hideFocus"in o)try{o.sheet.cssText.length||(n="e")}catch(e){18!=e.code&&(n="e")}if("e"==n&&(c+=1)<u)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==f(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in s)throw"LoadJS";s[r]=!0}function c(n,t){!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,s=c,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--c||r(o)},i=0;i<s;i++)h(e[i],t,n)}(e,function(e){a(i,e),n&&a({success:n,error:t},e),o(r,e)},i)}if(i.returnPromise)return new Promise(c);c()}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],s=e.length,o=s;for(n=function(e,n){n.length&&c.push(e),--o||t(c)};s--;)r=e[s],(i=u[r])?n(r,i):(f[r]=f[r]||[]).push(n)}(e,function(e){a(n,e)}),t},t.done=function(e){o(e,[])},t.reset=function(){s={},u={},f={}},t.isDefined=function(e){return e in s},t}(); \ No newline at end of file +loadjs=function(){var a=function(){},c={},u={},f={};function o(e,n){if(e){var t=f[e];if(u[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function l(e,n){e.call&&(e={success:e}),n.length?(e.error||a)(n):(e.success||a)(e)}function h(t,r,s,i){var c,o,e=document,n=s.async,u=(s.numRetries||0)+1,f=s.before||a,l=t.replace(/^(css|img)!/,"");i=i||0,/(^css!|\.css$)/.test(t)?((o=e.createElement("link")).rel="stylesheet",o.href=l,(c="hideFocus"in o)&&o.relList&&(c=0,o.rel="preload",o.as="style")):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=l:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(c)try{o.sheet.cssText.length||(n="e")}catch(e){18!=e.code&&(n="e")}if("e"==n){if((i+=1)<u)return h(t,r,s,i)}else if("preload"==o.rel&&"style"==o.as)return o.rel="stylesheet";r(t,n,e.defaultPrevented)})!==f(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,s;if(n&&n.trim&&(r=n),s=(r?t:n)||{},r){if(r in c)throw"LoadJS";c[r]=!0}function i(n,t){!function(e,r,n){var t,s,i=(e=e.push?e:[e]).length,c=i,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--i||r(o)},s=0;s<c;s++)h(e[s],t,n)}(e,function(e){l(s,e),n&&l({success:n,error:t},e),o(r,e)},s)}if(s.returnPromise)return new Promise(i);i()}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,s,i=[],c=e.length,o=c;for(n=function(e,n){n.length&&i.push(e),--o||t(i)};c--;)r=e[c],(s=u[r])?n(r,s):(f[r]=f[r]||[]).push(n)}(e,function(e){l(n,e)}),t},t.done=function(e){o(e,[])},t.reset=function(){c={},u={},f={}},t.isDefined=function(e){return e in c},t}(); \ No newline at end of file
1
updated README
1
.js
min
mit
muicss/loadjs
10062800
<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 } } ``` option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: function() { ...
0
Docs: Remove unnecessary whitespaces
10
.md
md
mit
tabalinas/jsgrid
10062801
<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 } } ``` option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: function() { ...
0
Docs: Remove unnecessary whitespaces
10
.md
md
mit
tabalinas/jsgrid
10062802
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062803
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062804
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062805
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062806
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062807
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062808
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062809
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062810
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062811
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062812
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062813
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062814
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062815
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062816
<NME> DocumentColorizingTransformer.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.Linq; using AvaloniaEdit.Document; namespace AvaloniaEdit.Rendering { /// <summary> /// Base class for <see cref="IVisualLineTransformer"/> that helps /// colorizing the document. Derived classes can work with document lines /// and text offsets and this class takes care of the visual lines and visual columns. /// </summary> public abstract class DocumentColorizingTransformer : ColorizingTransformer { private DocumentLine _currentDocumentLine; private int _firstLineStart; private int _currentDocumentLineStartOffset, _currentDocumentLineEndOffset; /// <summary> /// Gets the current ITextRunConstructionContext. /// </summary> protected ITextRunConstructionContext CurrentContext { get; private set; } /// <inheritdoc/> protected override void Colorize(ITextRunConstructionContext context) { CurrentContext = context ?? throw new ArgumentNullException(nameof(context)); _currentDocumentLine = context.VisualLine.FirstDocumentLine; _firstLineStart = _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; var currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; if (context.VisualLine.FirstDocumentLine == context.VisualLine.LastDocumentLine) { ColorizeLine(_currentDocumentLine); } else { ColorizeLine(_currentDocumentLine); // ColorizeLine modifies the visual line elements, loop through a copy of the line elements foreach (var e in context.VisualLine.Elements.ToArray()) { var elementOffset = _firstLineStart + e.RelativeTextOffset; if (elementOffset >= currentDocumentLineTotalEndOffset) { _currentDocumentLine = context.Document.GetLineByOffset(elementOffset); _currentDocumentLineStartOffset = _currentDocumentLine.Offset; _currentDocumentLineEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.Length; currentDocumentLineTotalEndOffset = _currentDocumentLineStartOffset + _currentDocumentLine.TotalLength; ColorizeLine(_currentDocumentLine); } } } _currentDocumentLine = null; CurrentContext = null; } /// <summary> /// Override this method to colorize an individual document line. /// </summary> protected abstract void ColorizeLine(DocumentLine line); /// <summary> /// Changes a part of the current document line. /// </summary> /// <param name="startOffset">Start offset of the region to change</param> /// <param name="endOffset">End offset of the region to change</param> /// <param name="action">Action that changes an individual <see cref="VisualLineElement"/>.</param> protected void ChangeLinePart(int startOffset, int endOffset, Action<VisualLineElement> action) { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart); } <MSG> fix bug asserting by checking the wrong field. <DFF> @@ -88,8 +88,8 @@ namespace AvaloniaEdit.Rendering { if (startOffset < _currentDocumentLineStartOffset || startOffset > _currentDocumentLineEndOffset) throw new ArgumentOutOfRangeException(nameof(startOffset), startOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); - if (endOffset < startOffset || endOffset > _currentDocumentLineEndOffset) - throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + startOffset + " and " + _currentDocumentLineEndOffset); + if (endOffset < _currentDocumentLineStartOffset || endOffset > _currentDocumentLineEndOffset) + throw new ArgumentOutOfRangeException(nameof(endOffset), endOffset, "Value must be between " + _currentDocumentLineStartOffset + " and " + _currentDocumentLineEndOffset); var vl = CurrentContext.VisualLine; var visualStart = vl.GetVisualColumn(startOffset - _firstLineStart); var visualEnd = vl.GetVisualColumn(endOffset - _firstLineStart);
2
fix bug asserting by checking the wrong field.
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062817
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); } fm.create = module.exports; fm.Model = options.Model; fm.Events = events; fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; Events.trigger.apply(this, [key, event].concat(args)); // Propagate by default propagate = (event.propagate === false) ? false : true; // Trigger the same // event on the parent view <MSG> More concise 'true by default' option <DFF> @@ -478,9 +478,7 @@ Events.trigger.apply(this, [key, event].concat(args)); // Propagate by default - propagate = (event.propagate === false) - ? false - : true; + propagate = (event.propagate !== false); // Trigger the same // event on the parent view
1
More concise 'true by default' option
3
.js
js
mit
ftlabs/fruitmachine
10062818
<NME> jsgrid.core.js <BEF> (function(window, $, undefined) { var JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID, JSGRID_ROW_DATA_KEY = "JSGridItem", JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", SORT_ORDER_ASC = "asc", SORT_ORDER_DESC = "desc", FIRST_PAGE_PLACEHOLDER = "{first}", PAGES_PLACEHOLDER = "{pages}", PREV_PAGE_PLACEHOLDER = "{prev}", NEXT_PAGE_PLACEHOLDER = "{next}", LAST_PAGE_PLACEHOLDER = "{last}", PAGE_INDEX_PLACEHOLDER = "{pageIndex}", PAGE_COUNT_PLACEHOLDER = "{pageCount}", EMPTY_HREF = "javascript:void(0);"; var getOrApply = function(value, context) { if($.isFunction(value)) { return value.apply(context, $.makeArray(arguments).slice(2)); } return value; }; var defaultController = { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }; function Grid(element, config) { var $element = $(element); $element.data(JSGRID_DATA_KEY, this); this._container = $element; this.data = []; this.fields = []; this._editingRow = null; this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._firstDisplayingPage = 1; this._init(config); this.render(); } Grid.prototype = { width: "auto", height: "auto", updateOnResize: true, rowClass: $.noop, rowRenderer: null, rowClick: function(args) { if(this.editing) { this.editItem($(args.event.target).closest("tr")); } }, noDataContent: "Not found", noDataRowClass: "jsgrid-nodata-row", heading: true, headerRowRenderer: null, headerRowClass: "jsgrid-header-row", filtering: false, filterRowRenderer: null, filterRowClass: "jsgrid-filter-row", inserting: false, insertRowRenderer: null, insertRowClass: "jsgrid-insert-row", editing: false, editRowRenderer: null, editRowClass: "jsgrid-edit-row", confirmDeleting: true, deleteConfirm: "Are you sure?", selecting: true, selectedRowClass: "jsgrid-selected-row", oddRowClass: "jsgrid-row", evenRowClass: "jsgrid-alt-row", sorting: false, sortableClass: "jsgrid-header-sortable", sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc", sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc", paging: false, 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: "...", pagerContainerClass: "jsgrid-pager-container", pagerClass: "jsgrid-pager", pagerNavButtonClass: "jsgrid-pager-nav-button", pageClass: "jsgrid-pager-page", currentPageClass: "jsgrid-pager-current-page", pageLoading: false, autoload: false, controller: defaultController, loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, onRefreshing: $.noop, onRefreshed: $.noop, onItemDeleting: $.noop, onItemDeleted: $.noop, onItemInserting: $.noop, onItemInserted: $.noop, onItemUpdating: $.noop, onItemUpdated: $.noop, onDataLoading: $.noop, onDataLoaded: $.noop, onOptionChanging: $.noop, onOptionChanged: $.noop, onError: $.noop, containerClass: "jsgrid", tableClass: "jsgrid-table", gridHeaderClass: "jsgrid-grid-header", gridBodyClass: "jsgrid-grid-body", _init: function(config) { $.extend(this, config); this._initLoadStrategy(); this._initController(); this._initFields(); this._attachWindowLoadResize(); this._attachWindowResizeCallback(); }, loadStrategy: function() { return this.pageLoading ? new jsGrid.loadStrategies.PageLoadingStrategy(this) : new jsGrid.loadStrategies.DirectLoadingStrategy(this); }, _initLoadStrategy: function() { this._loadStrategy = getOrApply(this.loadStrategy, this); }, _initController: function() { this._controller = $.extend({}, defaultController, getOrApply(this.controller, this)); }, loadIndicator: function(config) { return new jsGrid.LoadIndicator(config); }, _initFields: function() { var self = this; self.fields = $.map(self.fields, function(field) { if($.isPlainObject(field)) { var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field; field = new fieldConstructor(field); } field._grid = self; return field; }); }, _attachWindowLoadResize: function() { $(window).on("load", $.proxy(this._refreshSize, this)); }, _attachWindowResizeCallback: function() { if(this.updateOnResize) { $(window).on("resize", $.proxy(this._refreshSize, this)); } }, _detachWindowResizeCallback: function() { $(window).off("resize", this._refreshSize); }, option: function(key, value) { var optionChangingEventArgs, optionChangedEventArgs; if(arguments.length === 1) { return this[key]; } optionChangingEventArgs = { option: key, oldValue: this[key], newValue: value }; this._callEventHandler(this.onOptionChanging, optionChangingEventArgs); this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue); optionChangedEventArgs = { option: optionChangingEventArgs.option, value: optionChangingEventArgs.newValue }; this._callEventHandler(this.onOptionChanged, optionChangedEventArgs); }, _handleOptionChange: function(name, value) { this[name] = value; switch(name) { case "width": case "height": this._refreshSize(); break; case "rowClass": case "rowRenderer": case "rowClick": case "noDataText": case "noDataRowClass": case "noDataContent": case "selecting": case "selectedRowClass": case "oddRowClass": case "evenRowClass": this._refreshContent(); break; case "pageButtonCount": case "pagerFormat": case "pagePrevText": case "pageNextText": case "pageFirstText": case "pageLastText": case "pageNavigatorNextText": case "pageNavigatorPrevText": case "pagerClass": case "pagerNavButtonClass": case "pageClass": case "currentPageClass": this._refreshPager(); break; case "fields": this._initFields(); this.render(); break; case "data": case "editing": case "heading": case "filtering": case "inserting": case "paging": this.refresh(); break; case "pageLoading": this._initLoadStrategy(); this.search(); break; case "pageIndex": this.openPage(value); break; case "pageSize": this.refresh(); this.search(); break; case "editRowRenderer": case "editRowClass": this.cancelEdit(); break; default: this.render(); break; } }, destroy: function() { this._detachWindowResizeCallback(); this._clear(); this._container.removeData(JSGRID_DATA_KEY); }, render: function() { this._clear(); this._container.addClass(this.containerClass) .css("position", "relative") .append(this._createHeader()) .append(this._createBody()); this._pagerContainer = this._createPagerContainer(); this._loadIndicator = this._createLoadIndicator(); this.refresh(); return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); }, _createLoadIndicator: function() { return getOrApply(this.loadIndicator, this, { message: this.loadMessage, shading: this.loadShading, container: this._container }); }, _clear: function() { this.cancelEdit(); clearTimeout(this._loadingTimer); this._pagerContainer && this._pagerContainer.empty(); this._container.empty() .css({ position: "", width: "", height: "" }); }, _createHeader: function() { var $headerRow = this._headerRow = this._createHeaderRow(), $filterRow = this._filterRow = this._createFilterRow(), $insertRow = this._insertRow = this._createInsertRow(); var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass) .append($headerRow) .append($filterRow) .append($insertRow); var $header = this._header = $("<div>").addClass(this.gridHeaderClass) .append($headerGrid); return $header; }, _createBody: function() { var $content = this._content = $("<tbody>"); var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass) .append($content); var $body = this._body = $("<div>").addClass(this.gridBodyClass) .append($bodyGrid); return $body; }, _createPagerContainer: function() { var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container); return $(pagerContainer).addClass(this.pagerContainerClass); }, _eachField: function(callBack) { var self = this; $.each(this.fields, function(index, field) { return callBack.call(self, field, index); }); }, _createHeaderRow: function() { if($.isFunction(this.headerRowRenderer)) { return $(this.headerRowRenderer()); } var $result = $("<tr>").addClass(this.headerRowClass); this._eachField(function(field, index) { var $th = $("<th>").addClass(field.headercss || field.css) .appendTo($result) .append(field.headerTemplate ? field.headerTemplate() : "") .css("width", field.width); if(this.sorting && field.sorting) { $th.addClass(this.sortableClass) .on("click", $.proxy(function() { this.sort(index); }, this)); } }); return $result; }, _createFilterRow: function() { if($.isFunction(this.filterRowRenderer)) { return $(this.filterRowRenderer()); } var $result = $("<tr>").addClass(this.filterRowClass); this._eachField(function(field) { $("<td>").addClass(field.css) .appendTo($result) .append(field.filterTemplate ? field.filterTemplate() : "") .width(field.width); }); return $result; }, _createInsertRow: function() { if($.isFunction(this.insertRowRenderer)) { return $(this.insertRowRenderer()); } var $result = $("<tr>").addClass(this.insertRowClass); this._eachField(function(field) { $("<td>").addClass(field.css) .appendTo($result) .append(field.insertTemplate ? field.insertTemplate() : "") .width(field.width); }); return $result; }, _callEventHandler: function(handler, eventParams) { return handler.call(this, $.extend(eventParams, { grid: this })); }, reset: function() { this._resetSorting(); this._resetPager(); this.refresh(); }, _resetPager: function() { this._firstDisplayingPage = 1; this._setPage(1); }, _resetSorting: function() { this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._clearSortingCss(); }, refresh: function() { this._callEventHandler(this.onRefreshing); this.cancelEdit(); this._refreshHeading(); this._refreshFiltering(); this._refreshInserting(); this._refreshContent(); this._refreshPager(); this._refreshSize(); this._callEventHandler(this.onRefreshed); }, _refreshHeading: function() { this._headerRow.toggle(this.heading); }, _refreshFiltering: function() { this._filterRow.toggle(this.filtering); }, _refreshInserting: function() { this._insertRow.toggle(this.inserting); }, _refreshContent: function() { var $content = this._content; $content.empty(); if(!this.data.length) { $content.append(this._createNoDataRow()); return this; } var indexFrom = this._loadStrategy.firstDisplayIndex(); var indexTo = this._loadStrategy.lastDisplayIndex(); for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) { var item = this.data[itemIndex]; $content.append(this._createRow(item, itemIndex)); } }, _createNoDataRow: function() { var noDataContent = getOrApply(this.noDataContent, this); return $("<tr>").addClass(this.noDataRowClass) .append($("<td>").attr("colspan", this.fields.length).append(noDataContent)); }, _createNoDataContent: function () { return $.isFunction(this.noDataRenderer) ? this.noDataRenderer() : this.noDataText; }, _createRow: function(item, itemIndex) { var $result; if($.isFunction(this.rowRenderer)) { $result = $(this.rowRenderer(item, itemIndex)); } else { $result = $("<tr>"); this._renderCells($result, item); } $result.addClass(this._getRowClasses(item, itemIndex)) .data(JSGRID_ROW_DATA_KEY, item) .on("click", $.proxy(function(e) { this.rowClick({ item: item, itemIndex: itemIndex, event: e }); }, this)); if(this.selecting) { this._attachRowHover($result); } return $result; }, _getRowClasses: function(item, itemIndex) { var classes = []; classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass); classes.push(getOrApply(this.rowClass, this, item, itemIndex)); return classes.join(" "); }, _attachRowHover: function($row) { var selectedRowClass = this.selectedRowClass; $row.hover(function() { $(this).addClass(selectedRowClass); }, function() { $(this).removeClass(selectedRowClass); } ); }, _renderCells: function($row, item) { this._eachField(function(field) { $row.append(this._createCell(item, field)); }); return this; }, _createCell: function(item, field) { var $result; var fieldValue = item[field.name]; if($.isFunction(field.cellRenderer)) { $result = $(field.cellRenderer(fieldValue, item)); } else { $result = $("<td>").append(field.itemTemplate ? field.itemTemplate(fieldValue, item) : fieldValue); } $result.addClass(field.css) .width(field.width); field.align && $result.addClass("jsgrid-align-" + field.align); return $result; }, sort: function(field, order) { if($.isPlainObject(field)) { order = field.order; field = field.field; } this._clearSortingCss(); this._setSortingParams(field, order); this._setSortingCss(); return this._loadStrategy.sort(); }, _clearSortingCss: function() { this._headerRow.find("th") .removeClass(this.sortAscClass) .removeClass(this.sortDescClass); }, _setSortingParams: function(field, order) { field = this._normalizeSortingField(field); order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC); this._sortField = field; this._sortOrder = order; }, _normalizeSortingField: function(field) { if($.isNumeric(field)) { return this.fields[field]; } if(typeof field === "string") { return $.grep(this.fields, function (f) { return f.name === field; })[0]; } return field; }, _reversedSortOrder: function(order) { return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC); }, _setSortingCss: function() { var fieldIndex = $.inArray(this._sortField, this.fields); this._headerRow.find("th").eq(fieldIndex) .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass); }, _sortData: function() { var sortFactor = this._sortFactor(), sortField = this._sortField; if(sortField) { this.data.sort(function(item1, item2) { return sortFactor * sortField.sortingFunc(item1[sortField.name], item2[sortField.name]); }); } }, _sortFactor: function() { return this._sortOrder === SORT_ORDER_ASC ? 1 : -1; }, _itemsCount: function() { return this._loadStrategy.itemsCount(); }, _pagesCount: function() { var itemsCount = this._itemsCount(), pageSize = this.pageSize; return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0); }, _refreshPager: function() { var $pagerContainer = this._pagerContainer; $pagerContainer.empty(); if(this.paging && this._pagesCount() > 1) { $pagerContainer.show() .append(this._createPager()); } else { $pagerContainer.hide(); } }, _createPager: function() { var pageIndex = this.pageIndex, pageCount = this._pagesCount(), pagerParts = this.pagerFormat.split(" "); pagerParts = $.map(pagerParts, $.proxy(function(pagerPart) { var result = pagerPart; if(pagerPart === PAGES_PLACEHOLDER) { result = this._createPages(); } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) { result = pageIndex > 1 ? this._createPagerNavButton(this.pageFirstText, 1) : ""; } else if(pagerPart === PREV_PAGE_PLACEHOLDER) { result = pageIndex > 1 ? this._createPagerNavButton(this.pagePrevText, pageIndex - 1) : ""; } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) { result = pageIndex < pageCount ? this._createPagerNavButton(this.pageNextText, pageIndex + 1) : ""; } else if(pagerPart === LAST_PAGE_PLACEHOLDER) { result = pageIndex < pageCount ? this._createPagerNavButton(this.pageLastText, pageCount) : ""; } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) { result = pageIndex; } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) { result = pageCount; } return $.isArray(result) ? result.concat([" "]) : [result, " "]; }, this)); var $pager = $("<div>").addClass(this.pagerClass) .append(pagerParts); return $pager; }, _createPages: function() { var pageCount = this._pagesCount(), pageButtonCount = this.pageButtonCount, firstDisplayingPage = this._firstDisplayingPage, pages = [], pageNumber; if(firstDisplayingPage > 1) { pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages)); } for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) { pages.push(pageNumber === this.pageIndex ? this._createPagerCurrentPage() : this._createPagerPage(pageNumber)); } if((firstDisplayingPage + pageButtonCount - 1) < pageCount) { pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages)); } return pages; }, _createPagerNavButton: function(text, pageIndex) { return this._createPagerButton(text, this.pagerNavButtonClass, function() { this.openPage(pageIndex); }); }, _createPagerPageNavButton: function(text, handler) { return this._createPagerButton(text, this.pagerNavButtonClass, handler); }, _createPagerPage: function(pageIndex) { return this._createPagerButton(pageIndex, this.pageClass, function() { this.openPage(pageIndex); }); }, _createPagerButton: function(text, css, handler) { var $link = $("<a>").attr("href", EMPTY_HREF) .html(text) .on("click", $.proxy(handler, this)); return $("<span>").addClass(css).append($link); }, _createPagerCurrentPage: function() { return $("<span>") .addClass(this.pageClass) .addClass(this.currentPageClass) .text(this.pageIndex); }, _refreshSize: function() { this._refreshHeight(); this._refreshWidth(); }, _refreshWidth: function() { var $headerGrid = this._headerGrid, $bodyGrid = this._bodyGrid, width = this.width, scrollBarWidth = this._scrollBarWidth(), gridWidth; if(width === "auto") { $headerGrid.width("auto"); gridWidth = $headerGrid.outerWidth(); width = gridWidth + scrollBarWidth; } $headerGrid.width(""); $bodyGrid.width(""); this._header.css("padding-right", scrollBarWidth); this._container.width(width); gridWidth = $headerGrid.outerWidth(); $bodyGrid.width(gridWidth); }, _scrollBarWidth: (function() { var result; return function() { if(result === undefined) { var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"); var $ghostContent = $("<div style='height:100px;'></div>"); $ghostContainer.append($ghostContent).appendTo("body"); var width = $ghostContent.innerWidth(); $ghostContainer.css("overflow-y", "auto"); var widthExcludingScrollBar = $ghostContent.innerWidth(); $ghostContainer.remove(); result = width - widthExcludingScrollBar; } return result; }; })(), _refreshHeight: function() { var container = this._container, pagerContainer = this._pagerContainer, height = this.height, nonBodyHeight; container.height(height); if(height !== "auto") { height = container.height(); nonBodyHeight = this._header.outerHeight(true); if(pagerContainer.parents(container).length) { nonBodyHeight += pagerContainer.outerHeight(true); } this._body.outerHeight(height - nonBodyHeight); } }, showPrevPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1; this._refreshPager(); }, showNextPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount, pageCount = this._pagesCount(); this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount) ? pageCount - pageButtonCount + 1 : firstDisplayingPage + pageButtonCount; this._refreshPager(); }, openPage: function(pageIndex) { if(pageIndex < 1 || pageIndex > this._pagesCount()) return; this._setPage(pageIndex); this._loadStrategy.openPage(pageIndex); }, _setPage: function(pageIndex) { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this.pageIndex = pageIndex; if(pageIndex < firstDisplayingPage) { this._firstDisplayingPage = pageIndex; } if(pageIndex > firstDisplayingPage + pageButtonCount - 1) { this._firstDisplayingPage = pageIndex - pageButtonCount + 1; } }, _controllerCall: function(method, param, doneCallback) { this._showLoading(); var controller = this._controller; if(!controller || !controller[method]) { throw new Error("controller has no method '" + method + "'"); } return $.when(controller[method](param)) .done($.proxy(doneCallback, this)) .fail($.proxy(this._errorHandler, this)) .always($.proxy(this._hideLoading, this)); }, _errorHandler: function() { this._callEventHandler(this.onError, { args: $.makeArray(arguments) }); }, _showLoading: function() { clearTimeout(this._loadingTimer); this._loadingTimer = setTimeout($.proxy(function() { this._loadIndicator.show(); }, this), this.loadIndicationDelay); }, _hideLoading: function() { clearTimeout(this._loadingTimer); this._loadIndicator.hide(); }, search: function(filter) { this._resetSorting(); this._resetPager(); return this.loadData(filter); }, loadData: function(filter) { filter = filter || (this.filtering ? this._getFilter() : {}); $.extend(filter, this._loadStrategy.loadParams(), this._sortingParams()); this._callEventHandler(this.onDataLoading, { filter: filter }); return this._controllerCall("loadData", filter, function(loadedData) { this._loadStrategy.finishLoad(loadedData); this._callEventHandler(this.onDataLoaded, { data: loadedData }); }); }, _getFilter: function() { var result = {}; this._eachField(function(field) { if(field.filtering) { result[field.name] = field.filterValue(); } }); return result; }, _sortingParams: function() { if(this.sorting && this._sortField) { return { sortField: this._sortField.name, sortOrder: this._sortOrder }; } return {}; }, clearFilter: function() { var $filterRow = this._createFilterRow(); this._filterRow.replaceWith($filterRow); this._filterRow = $filterRow; return this.search(); }, insertItem: function(item) { var insertingItem = item || this._getInsertItem(); this._callEventHandler(this.onItemInserting, { item: insertingItem }); return this._controllerCall("insertItem", insertingItem, function(insertedItem) { insertedItem = insertedItem || insertingItem; this._loadStrategy.finishInsert(insertedItem); this._callEventHandler(this.onItemInserted, { item: insertedItem }); }); }, _getInsertItem: function() { var result = {}; this._eachField(function(field) { if(field.inserting) { result[field.name] = field.insertValue(); } }); return result; }, clearInsert: function() { var insertRow = this._createInsertRow(); this._insertRow.replaceWith(insertRow); this._insertRow = insertRow; this.refresh(); }, editItem: function(item) { var $row = this._rowByItem(item); if($row.length) { this._editRow($row); } }, _rowByItem: function(item) { if(item.jquery || item.nodeType) return $(item); return this._content.find("tr").filter(function() { return $.data(this, JSGRID_ROW_DATA_KEY) === item; }); }, _editRow: function($row) { if(!this.editing) return; if(this._editingRow) { this.cancelEdit(); } var item = $row.data(JSGRID_ROW_DATA_KEY), $editRow = this._createEditRow(item); this._editingRow = $row; $row.hide(); $editRow.insertAfter($row); $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); }, _createEditRow: function(item) { if($.isFunction(this.editRowRenderer)) { return $(this.editRowRenderer(item, this._itemIndex(item))); } var $result = $("<tr>").addClass(this.editRowClass); this._eachField(function(field) { $("<td>").addClass(field.css) .appendTo($result) .append(field.editTemplate ? field.editTemplate(item[field.name], item) : "") .width(field.width || "auto"); }); return $result; }, updateItem: function(item, editedItem) { if(arguments.length === 1) { editedItem = item; } var $row = item ? this._rowByItem(item) : this._editingRow; editedItem = editedItem || this._getEditedItem(); return this._updateRow($row, editedItem); }, _updateRow: function($updatingRow, editedItem) { var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), updatingItemIndex = this._itemIndex(updatingItem); $.extend(updatingItem, editedItem); this._callEventHandler(this.onItemUpdating, { row: $updatingRow, item: updatingItem, itemIndex: updatingItemIndex }); return this._controllerCall("updateItem", updatingItem, function(updatedItem) { updatedItem = updatedItem || updatingItem; this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); this._callEventHandler(this.onItemUpdated, { row: $updatingRow, item: updatedItem, itemIndex: updatingItemIndex }); }); }, _itemIndex: function(item) { return $.inArray(item, this.data); }, _finishUpdate: function($updatedRow, updatedItem, updatedItemIndex) { this.cancelEdit(); this.data[updatedItemIndex] = updatedItem; $updatedRow.replaceWith(this._createRow(updatedItem, updatedItemIndex)); }, _getEditedItem: function() { var result = {}; this._eachField(function(field) { if(field.editing) { result[field.name] = field.editValue(); } }); return result; }, cancelEdit: function() { if(!this._editingRow) { return; } var $row = this._editingRow, $editRow = $row.data(JSGRID_EDIT_ROW_DATA_KEY); $editRow.remove(); $row.show(); this._editingRow = null; }, deleteItem: function(item) { var $row = this._rowByItem(item); if(!$row.length) return; if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); }, _deleteRow: function($row) { var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), deletingItemIndex = this._itemIndex(deletingItem); this._callEventHandler(this.onItemDeleting, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); return this._controllerCall("deleteItem", deletingItem, function() { this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); this._callEventHandler(this.onItemDeleted, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); }); } }; $.fn.jsGrid = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSGRID_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance.render(); } } else { new Grid($element, config); } }); return result; }; window.jsGrid = { Grid: Grid, fields: [] }; }(window, jQuery)); var result = []; Object.keys(item).forEach(function(key,index) { var entry = ""; //Fields.length is greater than 0 when we are matching agaisnt fields //Field.length will be 0 when exporting header rows if (fields.length > 0){ var field = fields[index]; //Field may be excluded from data export if ("includeInDataExport" in field){ if (field.includeInDataExport){ //Field may be a select, which requires additional logic if (field.type === "select"){ var selectedItem = getItem(item, field); var resultItem = $.grep(field.items, function(item, index) { return item[field.valueField] === selectedItem; })[0] || ""; entry = resultItem[field.textField]; } else{ entry = getItem(item, field); } } else{ return; } } else{ entry = getItem(item, field); } if (transforms.hasOwnProperty(field.name)){ entry = transforms[field.name](entry); } } else{ entry = item[key]; } if (encapsulate){ entry = '"'+entry+'"'; } result.push(entry); }); return result.join(delimiter) + newline; }, getFilter: function() { var result = {}; this._eachField(function(field) { if(field.filtering) { this._setItemFieldValue(result, field, field.filterValue()); } }); return result; }, _sortingParams: function() { if(this.sorting && this._sortField) { return { sortField: this._sortField.name, sortOrder: this._sortOrder }; } return {}; }, getSorting: function() { var sortingParams = this._sortingParams(); return { field: sortingParams.sortField, order: sortingParams.sortOrder }; }, clearFilter: function() { var $filterRow = this._createFilterRow(); this._filterRow.replaceWith($filterRow); this._filterRow = $filterRow; return this.search(); }, insertItem: function(item) { var insertingItem = item || this._getValidatedInsertItem(); if(!insertingItem) return $.Deferred().reject().promise(); var args = this._callEventHandler(this.onItemInserting, { item: insertingItem }); return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) { insertedItem = insertedItem || insertingItem; this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation); this._callEventHandler(this.onItemInserted, { item: insertedItem }); }); }, _getValidatedInsertItem: function() { var item = this._getInsertItem(); return this._validateItem(item, this._insertRow) ? item : null; }, _getInsertItem: function() { var result = {}; this._eachField(function(field) { if(field.inserting) { this._setItemFieldValue(result, field, field.insertValue()); } }); return result; }, _validateItem: function(item, $row) { var validationErrors = []; var args = { item: item, itemIndex: this._rowIndex($row), row: $row }; this._eachField(function(field) { if(!field.validate || ($row === this._insertRow && !field.inserting) || ($row === this._getEditRow() && !field.editing)) return; var fieldValue = this._getItemFieldValue(item, field); var errors = this._validation.validate($.extend({ value: fieldValue, rules: field.validate }, args)); this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors); if(!errors.length) return; validationErrors.push.apply(validationErrors, $.map(errors, function(message) { return { field: field, message: message }; })); }); if(!validationErrors.length) return true; var invalidArgs = $.extend({ errors: validationErrors }, args); this._callEventHandler(this.onItemInvalid, invalidArgs); this.invalidNotify(invalidArgs); return false; }, _setCellValidity: function($cell, errors) { $cell .toggleClass(this.invalidClass, !!errors.length) .attr("title", errors.join("\n")); }, clearInsert: function() { var insertRow = this._createInsertRow(); this._insertRow.replaceWith(insertRow); this._insertRow = insertRow; this.refresh(); }, editItem: function(item) { var $row = this.rowByItem(item); if($row.length) { this._editRow($row); } }, rowByItem: function(item) { if(item.jquery || item.nodeType) return $(item); return this._content.find("tr").filter(function() { return $.data(this, JSGRID_ROW_DATA_KEY) === item; }); }, _editRow: function($row) { if(!this.editing) return; var item = $row.data(JSGRID_ROW_DATA_KEY); var args = this._callEventHandler(this.onItemEditing, { row: $row, item: item, itemIndex: this._itemIndex(item) }); if(args.cancel) return; if(this._editingRow) { this.cancelEdit(); } var $editRow = this._createEditRow(item); this._editingRow = $row; $row.hide(); $editRow.insertBefore($row); $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); }, _createEditRow: function(item) { if($.isFunction(this.editRowRenderer)) { return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) })); } var $result = $("<tr>").addClass(this.editRowClass); this._eachField(function(field) { var fieldValue = this._getItemFieldValue(item, field); this._prepareCell("<td>", field, "editcss") .append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item })) .appendTo($result); }); return $result; }, updateItem: function(item, editedItem) { if(arguments.length === 1) { editedItem = item; } var $row = item ? this.rowByItem(item) : this._editingRow; editedItem = editedItem || this._getValidatedEditedItem(); if(!editedItem) return; return this._updateRow($row, editedItem); }, _getValidatedEditedItem: function() { var item = this._getEditedItem(); return this._validateItem(item, this._getEditRow()) ? item : null; }, _updateRow: function($updatingRow, editedItem) { var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), updatingItemIndex = this._itemIndex(updatingItem), updatedItem = $.extend(true, {}, updatingItem, editedItem); var args = this._callEventHandler(this.onItemUpdating, { row: $updatingRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: updatingItem }); return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) { var previousItem = $.extend(true, {}, updatingItem); updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem); var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); this._callEventHandler(this.onItemUpdated, { row: $updatedRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: previousItem }); }); }, _rowIndex: function(row) { return this._content.children().index($(row)); }, _itemIndex: function(item) { return $.inArray(item, this.data); }, _finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) { this.cancelEdit(); this.data[updatedItemIndex] = updatedItem; var $updatedRow = this._createRow(updatedItem, updatedItemIndex); $updatingRow.replaceWith($updatedRow); return $updatedRow; }, _getEditedItem: function() { var result = {}; this._eachField(function(field) { if(field.editing) { this._setItemFieldValue(result, field, field.editValue()); } }); return result; }, cancelEdit: function() { if(!this._editingRow) return; var $row = this._editingRow, editingItem = $row.data(JSGRID_ROW_DATA_KEY), editingItemIndex = this._itemIndex(editingItem); this._callEventHandler(this.onItemEditCancelling, { row: $row, item: editingItem, itemIndex: editingItemIndex }); this._getEditRow().remove(); this._editingRow.show(); this._editingRow = null; }, _getEditRow: function() { return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY); }, deleteItem: function(item) { var $row = this.rowByItem(item); if(!$row.length) return; if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); }, _deleteRow: function($row) { var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), deletingItemIndex = this._itemIndex(deletingItem); var args = this._callEventHandler(this.onItemDeleting, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); return this._controllerCall("deleteItem", deletingItem, args.cancel, function() { this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); this._callEventHandler(this.onItemDeleted, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); }); } }; $.fn.jsGrid = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSGRID_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance.render(); } } else { new Grid($element, config); } }); return result; }; var fields = {}; var setDefaults = function(config) { var componentPrototype; if($.isPlainObject(config)) { componentPrototype = Grid.prototype; } else { componentPrototype = fields[config].prototype; config = arguments[1] || {}; } $.extend(componentPrototype, config); }; var locales = {}; var locale = function(lang) { var localeConfig = $.isPlainObject(lang) ? lang : locales[lang]; if(!localeConfig) throw Error("unknown locale " + lang); setLocale(jsGrid, localeConfig); }; var setLocale = function(obj, localeConfig) { $.each(localeConfig, function(field, value) { if($.isPlainObject(value)) { setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value); return; } if(obj.hasOwnProperty(field)) { obj[field] = value; } else { obj.prototype[field] = value; } }); }; window.jsGrid = { Grid: Grid, fields: fields, setDefaults: setDefaults, locales: locales, locale: locale, version: "@VERSION" }; }(window, jQuery)); <MSG> Formatting: Reformat jsgrid.core.js <DFF> @@ -1,1170 +1,1170 @@ -(function(window, $, undefined) { - - var JSGRID = "JSGrid", - JSGRID_DATA_KEY = JSGRID, - JSGRID_ROW_DATA_KEY = "JSGridItem", - JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", - - SORT_ORDER_ASC = "asc", - SORT_ORDER_DESC = "desc", - - FIRST_PAGE_PLACEHOLDER = "{first}", - PAGES_PLACEHOLDER = "{pages}", - PREV_PAGE_PLACEHOLDER = "{prev}", - NEXT_PAGE_PLACEHOLDER = "{next}", - LAST_PAGE_PLACEHOLDER = "{last}", - PAGE_INDEX_PLACEHOLDER = "{pageIndex}", - PAGE_COUNT_PLACEHOLDER = "{pageCount}", - - EMPTY_HREF = "javascript:void(0);"; - - var getOrApply = function(value, context) { - if($.isFunction(value)) { - return value.apply(context, $.makeArray(arguments).slice(2)); - } - return value; - }; - - var defaultController = { - loadData: $.noop, - insertItem: $.noop, - updateItem: $.noop, - deleteItem: $.noop - }; - - - function Grid(element, config) { - var $element = $(element); - - $element.data(JSGRID_DATA_KEY, this); - - this._container = $element; - - this.data = []; - this.fields = []; - - this._editingRow = null; - this._sortField = null; - this._sortOrder = SORT_ORDER_ASC; - this._firstDisplayingPage = 1; - - this._init(config); - this.render(); - } - - Grid.prototype = { - width: "auto", - height: "auto", - updateOnResize: true, - - rowClass: $.noop, - rowRenderer: null, - - rowClick: function(args) { - if(this.editing) { - this.editItem($(args.event.target).closest("tr")); - } - }, - - noDataContent: "Not found", - noDataRowClass: "jsgrid-nodata-row", - - heading: true, - headerRowRenderer: null, - headerRowClass: "jsgrid-header-row", - - filtering: false, - filterRowRenderer: null, - filterRowClass: "jsgrid-filter-row", - - inserting: false, - insertRowRenderer: null, - insertRowClass: "jsgrid-insert-row", - - editing: false, - editRowRenderer: null, - editRowClass: "jsgrid-edit-row", - - confirmDeleting: true, - deleteConfirm: "Are you sure?", - - selecting: true, - selectedRowClass: "jsgrid-selected-row", - oddRowClass: "jsgrid-row", - evenRowClass: "jsgrid-alt-row", - - sorting: false, - sortableClass: "jsgrid-header-sortable", - sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc", - sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc", - - paging: false, - 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: "...", - pagerContainerClass: "jsgrid-pager-container", - pagerClass: "jsgrid-pager", - pagerNavButtonClass: "jsgrid-pager-nav-button", - pageClass: "jsgrid-pager-page", - currentPageClass: "jsgrid-pager-current-page", - - pageLoading: false, - - autoload: false, - controller: defaultController, - - loadIndication: true, - loadIndicationDelay: 500, - loadMessage: "Please, wait...", - loadShading: true, - - onRefreshing: $.noop, - onRefreshed: $.noop, - onItemDeleting: $.noop, - onItemDeleted: $.noop, - onItemInserting: $.noop, - onItemInserted: $.noop, - onItemUpdating: $.noop, - onItemUpdated: $.noop, - onDataLoading: $.noop, - onDataLoaded: $.noop, - onOptionChanging: $.noop, - onOptionChanged: $.noop, - onError: $.noop, - - containerClass: "jsgrid", - tableClass: "jsgrid-table", - gridHeaderClass: "jsgrid-grid-header", - gridBodyClass: "jsgrid-grid-body", - - _init: function(config) { - $.extend(this, config); - this._initLoadStrategy(); - this._initController(); - this._initFields(); - this._attachWindowLoadResize(); - this._attachWindowResizeCallback(); - }, - - loadStrategy: function() { - return this.pageLoading - ? new jsGrid.loadStrategies.PageLoadingStrategy(this) - : new jsGrid.loadStrategies.DirectLoadingStrategy(this); - }, - - _initLoadStrategy: function() { - this._loadStrategy = getOrApply(this.loadStrategy, this); - }, - - _initController: function() { - this._controller = $.extend({}, defaultController, getOrApply(this.controller, this)); - }, - - loadIndicator: function(config) { - return new jsGrid.LoadIndicator(config); - }, - - _initFields: function() { - var self = this; - self.fields = $.map(self.fields, function(field) { - if($.isPlainObject(field)) { - var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field; - field = new fieldConstructor(field); - } - field._grid = self; - return field; - }); - }, - - _attachWindowLoadResize: function() { - $(window).on("load", $.proxy(this._refreshSize, this)); - }, - - _attachWindowResizeCallback: function() { - if(this.updateOnResize) { - $(window).on("resize", $.proxy(this._refreshSize, this)); - } - }, - - _detachWindowResizeCallback: function() { - $(window).off("resize", this._refreshSize); - }, - - option: function(key, value) { - var optionChangingEventArgs, - optionChangedEventArgs; - - if(arguments.length === 1) { - return this[key]; - } - - optionChangingEventArgs = { - option: key, - oldValue: this[key], - newValue: value - }; - this._callEventHandler(this.onOptionChanging, optionChangingEventArgs); - - this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue); - - optionChangedEventArgs = { - option: optionChangingEventArgs.option, - value: optionChangingEventArgs.newValue - }; - this._callEventHandler(this.onOptionChanged, optionChangedEventArgs); - }, - - _handleOptionChange: function(name, value) { - this[name] = value; - - switch(name) { - case "width": - case "height": - this._refreshSize(); - break; - case "rowClass": - case "rowRenderer": - case "rowClick": - case "noDataText": - case "noDataRowClass": - case "noDataContent": - case "selecting": - case "selectedRowClass": - case "oddRowClass": - case "evenRowClass": - this._refreshContent(); - break; - case "pageButtonCount": - case "pagerFormat": - case "pagePrevText": - case "pageNextText": - case "pageFirstText": - case "pageLastText": - case "pageNavigatorNextText": - case "pageNavigatorPrevText": - case "pagerClass": - case "pagerNavButtonClass": - case "pageClass": - case "currentPageClass": - this._refreshPager(); - break; - case "fields": - this._initFields(); - this.render(); - break; - case "data": - case "editing": - case "heading": - case "filtering": - case "inserting": - case "paging": - this.refresh(); - break; - case "pageLoading": - this._initLoadStrategy(); - this.search(); - break; - case "pageIndex": - this.openPage(value); - break; - case "pageSize": - this.refresh(); - this.search(); - break; - case "editRowRenderer": - case "editRowClass": - this.cancelEdit(); - break; - default: - this.render(); - break; - } - }, - - destroy: function() { - this._detachWindowResizeCallback(); - this._clear(); - this._container.removeData(JSGRID_DATA_KEY); - }, - - render: function() { - this._clear(); - - this._container.addClass(this.containerClass) - .css("position", "relative") - .append(this._createHeader()) - .append(this._createBody()); - - this._pagerContainer = this._createPagerContainer(); - this._loadIndicator = this._createLoadIndicator(); - - this.refresh(); - - return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); - }, - - _createLoadIndicator: function() { - return getOrApply(this.loadIndicator, this, { - message: this.loadMessage, - shading: this.loadShading, - container: this._container - }); - }, - - _clear: function() { - this.cancelEdit(); - - clearTimeout(this._loadingTimer); - - this._pagerContainer && this._pagerContainer.empty(); - - this._container.empty() - .css({ position: "", width: "", height: "" }); - }, - - _createHeader: function() { - var $headerRow = this._headerRow = this._createHeaderRow(), - $filterRow = this._filterRow = this._createFilterRow(), - $insertRow = this._insertRow = this._createInsertRow(); - - var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass) - .append($headerRow) - .append($filterRow) - .append($insertRow); - - var $header = this._header = $("<div>").addClass(this.gridHeaderClass) - .append($headerGrid); - - return $header; - }, - - _createBody: function() { - var $content = this._content = $("<tbody>"); - - var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass) - .append($content); - - var $body = this._body = $("<div>").addClass(this.gridBodyClass) - .append($bodyGrid); - - return $body; - }, - - _createPagerContainer: function() { - var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container); - return $(pagerContainer).addClass(this.pagerContainerClass); - }, - - _eachField: function(callBack) { - var self = this; - $.each(this.fields, function(index, field) { - return callBack.call(self, field, index); - }); - }, - - _createHeaderRow: function() { - if($.isFunction(this.headerRowRenderer)) { - return $(this.headerRowRenderer()); - } - - var $result = $("<tr>").addClass(this.headerRowClass); - - this._eachField(function(field, index) { - var $th = $("<th>").addClass(field.headercss || field.css) - .appendTo($result) - .append(field.headerTemplate ? field.headerTemplate() : "") - .css("width", field.width); - - if(this.sorting && field.sorting) { - $th.addClass(this.sortableClass) - .on("click", $.proxy(function() { - this.sort(index); - }, this)); - } - }); - - return $result; - }, - - _createFilterRow: function() { - if($.isFunction(this.filterRowRenderer)) { - return $(this.filterRowRenderer()); - } - - var $result = $("<tr>").addClass(this.filterRowClass); - - this._eachField(function(field) { - $("<td>").addClass(field.css) - .appendTo($result) - .append(field.filterTemplate ? field.filterTemplate() : "") - .width(field.width); - }); - - return $result; - }, - - _createInsertRow: function() { - if($.isFunction(this.insertRowRenderer)) { - return $(this.insertRowRenderer()); - } - - var $result = $("<tr>").addClass(this.insertRowClass); - - this._eachField(function(field) { - $("<td>").addClass(field.css) - .appendTo($result) - .append(field.insertTemplate ? field.insertTemplate() : "") - .width(field.width); - }); - - return $result; - }, - - _callEventHandler: function(handler, eventParams) { - return handler.call(this, $.extend(eventParams, { - grid: this - })); - }, - - reset: function() { - this._resetSorting(); - this._resetPager(); - this.refresh(); - }, - - _resetPager: function() { - this._firstDisplayingPage = 1; - this._setPage(1); - }, - - _resetSorting: function() { - this._sortField = null; - this._sortOrder = SORT_ORDER_ASC; - this._clearSortingCss(); - }, - - refresh: function() { - this._callEventHandler(this.onRefreshing); - - this.cancelEdit(); - - this._refreshHeading(); - this._refreshFiltering(); - this._refreshInserting(); - this._refreshContent(); - this._refreshPager(); - this._refreshSize(); - - this._callEventHandler(this.onRefreshed); - }, - - _refreshHeading: function() { - this._headerRow.toggle(this.heading); - }, - - _refreshFiltering: function() { - this._filterRow.toggle(this.filtering); - }, - - _refreshInserting: function() { - this._insertRow.toggle(this.inserting); - }, - - _refreshContent: function() { - var $content = this._content; - $content.empty(); - - if(!this.data.length) { - $content.append(this._createNoDataRow()); - return this; - } - - var indexFrom = this._loadStrategy.firstDisplayIndex(); - var indexTo = this._loadStrategy.lastDisplayIndex(); - - for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) { - var item = this.data[itemIndex]; - $content.append(this._createRow(item, itemIndex)); - } - }, - - _createNoDataRow: function() { - var noDataContent = getOrApply(this.noDataContent, this); - return $("<tr>").addClass(this.noDataRowClass) - .append($("<td>").attr("colspan", this.fields.length).append(noDataContent)); - }, - - _createNoDataContent: function () { - return $.isFunction(this.noDataRenderer) - ? this.noDataRenderer() - : this.noDataText; - }, - - _createRow: function(item, itemIndex) { - var $result; - - if($.isFunction(this.rowRenderer)) { - $result = $(this.rowRenderer(item, itemIndex)); - } else { - $result = $("<tr>"); - this._renderCells($result, item); - } - - $result.addClass(this._getRowClasses(item, itemIndex)) - .data(JSGRID_ROW_DATA_KEY, item) - .on("click", $.proxy(function(e) { - this.rowClick({ - item: item, - itemIndex: itemIndex, - event: e - }); - }, this)); - - if(this.selecting) { - this._attachRowHover($result); - } - - return $result; - }, - - _getRowClasses: function(item, itemIndex) { - var classes = []; - classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass); - classes.push(getOrApply(this.rowClass, this, item, itemIndex)); - return classes.join(" "); - }, - - _attachRowHover: function($row) { - var selectedRowClass = this.selectedRowClass; - $row.hover(function() { - $(this).addClass(selectedRowClass); - }, - function() { - $(this).removeClass(selectedRowClass); - } - ); - }, - - _renderCells: function($row, item) { - this._eachField(function(field) { - $row.append(this._createCell(item, field)); - }); - return this; - }, - - _createCell: function(item, field) { - var $result; - var fieldValue = item[field.name]; - - if($.isFunction(field.cellRenderer)) { - $result = $(field.cellRenderer(fieldValue, item)); - } else { - $result = $("<td>").append(field.itemTemplate ? field.itemTemplate(fieldValue, item) : fieldValue); - } - - $result.addClass(field.css) - .width(field.width); - - field.align && $result.addClass("jsgrid-align-" + field.align); - - return $result; - }, - - sort: function(field, order) { - if($.isPlainObject(field)) { - order = field.order; - field = field.field; - } - - this._clearSortingCss(); - this._setSortingParams(field, order); - this._setSortingCss(); - return this._loadStrategy.sort(); - }, - - _clearSortingCss: function() { - this._headerRow.find("th") - .removeClass(this.sortAscClass) - .removeClass(this.sortDescClass); - }, - - _setSortingParams: function(field, order) { - field = this._normalizeSortingField(field); - order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC); - - this._sortField = field; - this._sortOrder = order; - }, - - _normalizeSortingField: function(field) { - if($.isNumeric(field)) { - return this.fields[field]; - } - - if(typeof field === "string") { - return $.grep(this.fields, function (f) { - return f.name === field; - })[0]; - } - - return field; - }, - - _reversedSortOrder: function(order) { - return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC); - }, - - _setSortingCss: function() { - var fieldIndex = $.inArray(this._sortField, this.fields); - - this._headerRow.find("th").eq(fieldIndex) - .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass); - }, - - _sortData: function() { - var sortFactor = this._sortFactor(), - sortField = this._sortField; - - if(sortField) { - this.data.sort(function(item1, item2) { - return sortFactor * sortField.sortingFunc(item1[sortField.name], item2[sortField.name]); - }); - } - }, - - _sortFactor: function() { - return this._sortOrder === SORT_ORDER_ASC ? 1 : -1; - }, - - _itemsCount: function() { - return this._loadStrategy.itemsCount(); - }, - - _pagesCount: function() { - var itemsCount = this._itemsCount(), - pageSize = this.pageSize; - return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0); - }, - - _refreshPager: function() { - var $pagerContainer = this._pagerContainer; - $pagerContainer.empty(); - - if(this.paging && this._pagesCount() > 1) { - $pagerContainer.show() - .append(this._createPager()); - } else { - $pagerContainer.hide(); - } - }, - - _createPager: function() { - var pageIndex = this.pageIndex, - pageCount = this._pagesCount(), - pagerParts = this.pagerFormat.split(" "); - - pagerParts = $.map(pagerParts, $.proxy(function(pagerPart) { - var result = pagerPart; - - if(pagerPart === PAGES_PLACEHOLDER) { - result = this._createPages(); - } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) { - result = pageIndex > 1 ? this._createPagerNavButton(this.pageFirstText, 1) : ""; - } else if(pagerPart === PREV_PAGE_PLACEHOLDER) { - result = pageIndex > 1 ? this._createPagerNavButton(this.pagePrevText, pageIndex - 1) : ""; - } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) { - result = pageIndex < pageCount ? this._createPagerNavButton(this.pageNextText, pageIndex + 1) : ""; - } else if(pagerPart === LAST_PAGE_PLACEHOLDER) { - result = pageIndex < pageCount ? this._createPagerNavButton(this.pageLastText, pageCount) : ""; - } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) { - result = pageIndex; - } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) { - result = pageCount; - } - - return $.isArray(result) ? result.concat([" "]) : [result, " "]; - }, this)); - - var $pager = $("<div>").addClass(this.pagerClass) - .append(pagerParts); - - return $pager; - }, - - _createPages: function() { - var pageCount = this._pagesCount(), - pageButtonCount = this.pageButtonCount, - firstDisplayingPage = this._firstDisplayingPage, - pages = [], - pageNumber; - - if(firstDisplayingPage > 1) { - pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages)); - } - - for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) { - pages.push(pageNumber === this.pageIndex - ? this._createPagerCurrentPage() - : this._createPagerPage(pageNumber)); - } - - if((firstDisplayingPage + pageButtonCount - 1) < pageCount) { - pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages)); - } - - return pages; - }, - - _createPagerNavButton: function(text, pageIndex) { - return this._createPagerButton(text, this.pagerNavButtonClass, function() { - this.openPage(pageIndex); - }); - }, - - _createPagerPageNavButton: function(text, handler) { - return this._createPagerButton(text, this.pagerNavButtonClass, handler); - }, - - _createPagerPage: function(pageIndex) { - return this._createPagerButton(pageIndex, this.pageClass, function() { - this.openPage(pageIndex); - }); - }, - - _createPagerButton: function(text, css, handler) { - var $link = $("<a>").attr("href", EMPTY_HREF) - .html(text) - .on("click", $.proxy(handler, this)); - - return $("<span>").addClass(css).append($link); - }, - - _createPagerCurrentPage: function() { - return $("<span>") - .addClass(this.pageClass) - .addClass(this.currentPageClass) - .text(this.pageIndex); - }, - - _refreshSize: function() { - this._refreshHeight(); - this._refreshWidth(); - }, - - _refreshWidth: function() { - var $headerGrid = this._headerGrid, - $bodyGrid = this._bodyGrid, - width = this.width, - scrollBarWidth = this._scrollBarWidth(), - gridWidth; - - if(width === "auto") { - $headerGrid.width("auto"); - gridWidth = $headerGrid.outerWidth(); - width = gridWidth + scrollBarWidth; - } - - $headerGrid.width(""); - $bodyGrid.width(""); - this._header.css("padding-right", scrollBarWidth); - this._container.width(width); - gridWidth = $headerGrid.outerWidth(); - $bodyGrid.width(gridWidth); - }, - - _scrollBarWidth: (function() { - var result; - - return function() { - if(result === undefined) { - var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"); - var $ghostContent = $("<div style='height:100px;'></div>"); - $ghostContainer.append($ghostContent).appendTo("body"); - var width = $ghostContent.innerWidth(); - $ghostContainer.css("overflow-y", "auto"); - var widthExcludingScrollBar = $ghostContent.innerWidth(); - $ghostContainer.remove(); - result = width - widthExcludingScrollBar; - } - return result; - }; - })(), - - _refreshHeight: function() { - var container = this._container, - pagerContainer = this._pagerContainer, - height = this.height, - nonBodyHeight; - - container.height(height); - - if(height !== "auto") { - height = container.height(); - - nonBodyHeight = this._header.outerHeight(true); - if(pagerContainer.parents(container).length) { - nonBodyHeight += pagerContainer.outerHeight(true); - } - - this._body.outerHeight(height - nonBodyHeight); - } - }, - - showPrevPages: function() { - var firstDisplayingPage = this._firstDisplayingPage, - pageButtonCount = this.pageButtonCount; - - this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1; - - this._refreshPager(); - }, - - showNextPages: function() { - var firstDisplayingPage = this._firstDisplayingPage, - pageButtonCount = this.pageButtonCount, - pageCount = this._pagesCount(); - - this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount) - ? pageCount - pageButtonCount + 1 - : firstDisplayingPage + pageButtonCount; - - this._refreshPager(); - }, - - openPage: function(pageIndex) { - if(pageIndex < 1 || pageIndex > this._pagesCount()) - return; - - this._setPage(pageIndex); - this._loadStrategy.openPage(pageIndex); - }, - - _setPage: function(pageIndex) { - var firstDisplayingPage = this._firstDisplayingPage, - pageButtonCount = this.pageButtonCount; - - this.pageIndex = pageIndex; - - if(pageIndex < firstDisplayingPage) { - this._firstDisplayingPage = pageIndex; - } - - if(pageIndex > firstDisplayingPage + pageButtonCount - 1) { - this._firstDisplayingPage = pageIndex - pageButtonCount + 1; - } - }, - - _controllerCall: function(method, param, doneCallback) { - this._showLoading(); - - var controller = this._controller; - if(!controller || !controller[method]) { - throw new Error("controller has no method '" + method + "'"); - } - - return $.when(controller[method](param)) - .done($.proxy(doneCallback, this)) - .fail($.proxy(this._errorHandler, this)) - .always($.proxy(this._hideLoading, this)); - }, - - _errorHandler: function() { - this._callEventHandler(this.onError, { - args: $.makeArray(arguments) - }); - }, - - _showLoading: function() { - clearTimeout(this._loadingTimer); - - this._loadingTimer = setTimeout($.proxy(function() { - this._loadIndicator.show(); - }, this), this.loadIndicationDelay); - }, - - _hideLoading: function() { - clearTimeout(this._loadingTimer); - this._loadIndicator.hide(); - }, - - search: function(filter) { - this._resetSorting(); - this._resetPager(); - return this.loadData(filter); - }, - - loadData: function(filter) { - filter = filter || (this.filtering ? this._getFilter() : {}); - - $.extend(filter, this._loadStrategy.loadParams(), this._sortingParams()); - - this._callEventHandler(this.onDataLoading, { - filter: filter - }); - - return this._controllerCall("loadData", filter, function(loadedData) { - this._loadStrategy.finishLoad(loadedData); - - this._callEventHandler(this.onDataLoaded, { - data: loadedData - }); - }); - }, - - _getFilter: function() { - var result = {}; - this._eachField(function(field) { - if(field.filtering) { - result[field.name] = field.filterValue(); - } - }); - return result; - }, - - _sortingParams: function() { - if(this.sorting && this._sortField) { - return { - sortField: this._sortField.name, - sortOrder: this._sortOrder - }; - } - return {}; - }, - - clearFilter: function() { - var $filterRow = this._createFilterRow(); - this._filterRow.replaceWith($filterRow); - this._filterRow = $filterRow; - return this.search(); - }, - - insertItem: function(item) { - var insertingItem = item || this._getInsertItem(); - - this._callEventHandler(this.onItemInserting, { - item: insertingItem - }); - - return this._controllerCall("insertItem", insertingItem, function(insertedItem) { - insertedItem = insertedItem || insertingItem; - this._loadStrategy.finishInsert(insertedItem); - - this._callEventHandler(this.onItemInserted, { - item: insertedItem - }); - }); - }, - - _getInsertItem: function() { - var result = {}; - this._eachField(function(field) { - if(field.inserting) { - result[field.name] = field.insertValue(); - } - }); - return result; - }, - - clearInsert: function() { - var insertRow = this._createInsertRow(); - this._insertRow.replaceWith(insertRow); - this._insertRow = insertRow; - this.refresh(); - }, - - editItem: function(item) { - var $row = this._rowByItem(item); - if($row.length) { - this._editRow($row); - } - }, - - _rowByItem: function(item) { - if(item.jquery || item.nodeType) - return $(item); - - return this._content.find("tr").filter(function() { - return $.data(this, JSGRID_ROW_DATA_KEY) === item; - }); - }, - - _editRow: function($row) { - if(!this.editing) - return; - - if(this._editingRow) { - this.cancelEdit(); - } - - var item = $row.data(JSGRID_ROW_DATA_KEY), - $editRow = this._createEditRow(item); - - this._editingRow = $row; - $row.hide(); - $editRow.insertAfter($row); - $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); - }, - - _createEditRow: function(item) { - if($.isFunction(this.editRowRenderer)) { - return $(this.editRowRenderer(item, this._itemIndex(item))); - } - - var $result = $("<tr>").addClass(this.editRowClass); - - this._eachField(function(field) { - $("<td>").addClass(field.css) - .appendTo($result) - .append(field.editTemplate ? field.editTemplate(item[field.name], item) : "") - .width(field.width || "auto"); - }); - - return $result; - }, - - updateItem: function(item, editedItem) { - if(arguments.length === 1) { - editedItem = item; - } - - var $row = item ? this._rowByItem(item) : this._editingRow; - editedItem = editedItem || this._getEditedItem(); - - return this._updateRow($row, editedItem); - }, - - _updateRow: function($updatingRow, editedItem) { - var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), - updatingItemIndex = this._itemIndex(updatingItem); - - $.extend(updatingItem, editedItem); - - this._callEventHandler(this.onItemUpdating, { - row: $updatingRow, - item: updatingItem, - itemIndex: updatingItemIndex - }); - - return this._controllerCall("updateItem", updatingItem, function(updatedItem) { - updatedItem = updatedItem || updatingItem; - this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); - - this._callEventHandler(this.onItemUpdated, { - row: $updatingRow, - item: updatedItem, - itemIndex: updatingItemIndex - }); - }); - }, - - _itemIndex: function(item) { - return $.inArray(item, this.data); - }, - - _finishUpdate: function($updatedRow, updatedItem, updatedItemIndex) { - this.cancelEdit(); - this.data[updatedItemIndex] = updatedItem; - $updatedRow.replaceWith(this._createRow(updatedItem, updatedItemIndex)); - }, - - _getEditedItem: function() { - var result = {}; - this._eachField(function(field) { - if(field.editing) { - result[field.name] = field.editValue(); - } - }); - return result; - }, - - cancelEdit: function() { - if(!this._editingRow) { - return; - } - - var $row = this._editingRow, - $editRow = $row.data(JSGRID_EDIT_ROW_DATA_KEY); - - $editRow.remove(); - $row.show(); - this._editingRow = null; - }, - - deleteItem: function(item) { - var $row = this._rowByItem(item); - - if(!$row.length) - return; - - if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) - return; - - return this._deleteRow($row); - }, - - _deleteRow: function($row) { - var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), - deletingItemIndex = this._itemIndex(deletingItem); - - this._callEventHandler(this.onItemDeleting, { - row: $row, - item: deletingItem, - itemIndex: deletingItemIndex - }); - - return this._controllerCall("deleteItem", deletingItem, function() { - this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); - - this._callEventHandler(this.onItemDeleted, { - row: $row, - item: deletingItem, - itemIndex: deletingItemIndex - }); - }); - } - }; - - $.fn.jsGrid = function(config) { - var args = $.makeArray(arguments), - methodArgs = args.slice(1), - result = this; - - this.each(function() { - var $element = $(this), - instance = $element.data(JSGRID_DATA_KEY), - methodResult; - - if(instance) { - if(typeof config === "string") { - methodResult = instance[config].apply(instance, methodArgs); - if(methodResult !== undefined && methodResult !== instance) { - result = methodResult; - return false; - } - } else { - instance._detachWindowResizeCallback(); - instance._init(config); - instance.render(); - } - } else { - new Grid($element, config); - } - }); - - return result; - }; - - window.jsGrid = { - Grid: Grid, - fields: [] - }; - -}(window, jQuery)); \ No newline at end of file +(function(window, $, undefined) { + + var JSGRID = "JSGrid", + JSGRID_DATA_KEY = JSGRID, + JSGRID_ROW_DATA_KEY = "JSGridItem", + JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", + + SORT_ORDER_ASC = "asc", + SORT_ORDER_DESC = "desc", + + FIRST_PAGE_PLACEHOLDER = "{first}", + PAGES_PLACEHOLDER = "{pages}", + PREV_PAGE_PLACEHOLDER = "{prev}", + NEXT_PAGE_PLACEHOLDER = "{next}", + LAST_PAGE_PLACEHOLDER = "{last}", + PAGE_INDEX_PLACEHOLDER = "{pageIndex}", + PAGE_COUNT_PLACEHOLDER = "{pageCount}", + + EMPTY_HREF = "javascript:void(0);"; + + var getOrApply = function(value, context) { + if($.isFunction(value)) { + return value.apply(context, $.makeArray(arguments).slice(2)); + } + return value; + }; + + var defaultController = { + loadData: $.noop, + insertItem: $.noop, + updateItem: $.noop, + deleteItem: $.noop + }; + + + function Grid(element, config) { + var $element = $(element); + + $element.data(JSGRID_DATA_KEY, this); + + this._container = $element; + + this.data = []; + this.fields = []; + + this._editingRow = null; + this._sortField = null; + this._sortOrder = SORT_ORDER_ASC; + this._firstDisplayingPage = 1; + + this._init(config); + this.render(); + } + + Grid.prototype = { + width: "auto", + height: "auto", + updateOnResize: true, + + rowClass: $.noop, + rowRenderer: null, + + rowClick: function(args) { + if(this.editing) { + this.editItem($(args.event.target).closest("tr")); + } + }, + + noDataContent: "Not found", + noDataRowClass: "jsgrid-nodata-row", + + heading: true, + headerRowRenderer: null, + headerRowClass: "jsgrid-header-row", + + filtering: false, + filterRowRenderer: null, + filterRowClass: "jsgrid-filter-row", + + inserting: false, + insertRowRenderer: null, + insertRowClass: "jsgrid-insert-row", + + editing: false, + editRowRenderer: null, + editRowClass: "jsgrid-edit-row", + + confirmDeleting: true, + deleteConfirm: "Are you sure?", + + selecting: true, + selectedRowClass: "jsgrid-selected-row", + oddRowClass: "jsgrid-row", + evenRowClass: "jsgrid-alt-row", + + sorting: false, + sortableClass: "jsgrid-header-sortable", + sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc", + sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc", + + paging: false, + 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: "...", + pagerContainerClass: "jsgrid-pager-container", + pagerClass: "jsgrid-pager", + pagerNavButtonClass: "jsgrid-pager-nav-button", + pageClass: "jsgrid-pager-page", + currentPageClass: "jsgrid-pager-current-page", + + pageLoading: false, + + autoload: false, + controller: defaultController, + + loadIndication: true, + loadIndicationDelay: 500, + loadMessage: "Please, wait...", + loadShading: true, + + onRefreshing: $.noop, + onRefreshed: $.noop, + onItemDeleting: $.noop, + onItemDeleted: $.noop, + onItemInserting: $.noop, + onItemInserted: $.noop, + onItemUpdating: $.noop, + onItemUpdated: $.noop, + onDataLoading: $.noop, + onDataLoaded: $.noop, + onOptionChanging: $.noop, + onOptionChanged: $.noop, + onError: $.noop, + + containerClass: "jsgrid", + tableClass: "jsgrid-table", + gridHeaderClass: "jsgrid-grid-header", + gridBodyClass: "jsgrid-grid-body", + + _init: function(config) { + $.extend(this, config); + this._initLoadStrategy(); + this._initController(); + this._initFields(); + this._attachWindowLoadResize(); + this._attachWindowResizeCallback(); + }, + + loadStrategy: function() { + return this.pageLoading + ? new jsGrid.loadStrategies.PageLoadingStrategy(this) + : new jsGrid.loadStrategies.DirectLoadingStrategy(this); + }, + + _initLoadStrategy: function() { + this._loadStrategy = getOrApply(this.loadStrategy, this); + }, + + _initController: function() { + this._controller = $.extend({}, defaultController, getOrApply(this.controller, this)); + }, + + loadIndicator: function(config) { + return new jsGrid.LoadIndicator(config); + }, + + _initFields: function() { + var self = this; + self.fields = $.map(self.fields, function(field) { + if($.isPlainObject(field)) { + var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field; + field = new fieldConstructor(field); + } + field._grid = self; + return field; + }); + }, + + _attachWindowLoadResize: function() { + $(window).on("load", $.proxy(this._refreshSize, this)); + }, + + _attachWindowResizeCallback: function() { + if(this.updateOnResize) { + $(window).on("resize", $.proxy(this._refreshSize, this)); + } + }, + + _detachWindowResizeCallback: function() { + $(window).off("resize", this._refreshSize); + }, + + option: function(key, value) { + var optionChangingEventArgs, + optionChangedEventArgs; + + if(arguments.length === 1) { + return this[key]; + } + + optionChangingEventArgs = { + option: key, + oldValue: this[key], + newValue: value + }; + this._callEventHandler(this.onOptionChanging, optionChangingEventArgs); + + this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue); + + optionChangedEventArgs = { + option: optionChangingEventArgs.option, + value: optionChangingEventArgs.newValue + }; + this._callEventHandler(this.onOptionChanged, optionChangedEventArgs); + }, + + _handleOptionChange: function(name, value) { + this[name] = value; + + switch(name) { + case "width": + case "height": + this._refreshSize(); + break; + case "rowClass": + case "rowRenderer": + case "rowClick": + case "noDataText": + case "noDataRowClass": + case "noDataContent": + case "selecting": + case "selectedRowClass": + case "oddRowClass": + case "evenRowClass": + this._refreshContent(); + break; + case "pageButtonCount": + case "pagerFormat": + case "pagePrevText": + case "pageNextText": + case "pageFirstText": + case "pageLastText": + case "pageNavigatorNextText": + case "pageNavigatorPrevText": + case "pagerClass": + case "pagerNavButtonClass": + case "pageClass": + case "currentPageClass": + this._refreshPager(); + break; + case "fields": + this._initFields(); + this.render(); + break; + case "data": + case "editing": + case "heading": + case "filtering": + case "inserting": + case "paging": + this.refresh(); + break; + case "pageLoading": + this._initLoadStrategy(); + this.search(); + break; + case "pageIndex": + this.openPage(value); + break; + case "pageSize": + this.refresh(); + this.search(); + break; + case "editRowRenderer": + case "editRowClass": + this.cancelEdit(); + break; + default: + this.render(); + break; + } + }, + + destroy: function() { + this._detachWindowResizeCallback(); + this._clear(); + this._container.removeData(JSGRID_DATA_KEY); + }, + + render: function() { + this._clear(); + + this._container.addClass(this.containerClass) + .css("position", "relative") + .append(this._createHeader()) + .append(this._createBody()); + + this._pagerContainer = this._createPagerContainer(); + this._loadIndicator = this._createLoadIndicator(); + + this.refresh(); + + return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); + }, + + _createLoadIndicator: function() { + return getOrApply(this.loadIndicator, this, { + message: this.loadMessage, + shading: this.loadShading, + container: this._container + }); + }, + + _clear: function() { + this.cancelEdit(); + + clearTimeout(this._loadingTimer); + + this._pagerContainer && this._pagerContainer.empty(); + + this._container.empty() + .css({ position: "", width: "", height: "" }); + }, + + _createHeader: function() { + var $headerRow = this._headerRow = this._createHeaderRow(), + $filterRow = this._filterRow = this._createFilterRow(), + $insertRow = this._insertRow = this._createInsertRow(); + + var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass) + .append($headerRow) + .append($filterRow) + .append($insertRow); + + var $header = this._header = $("<div>").addClass(this.gridHeaderClass) + .append($headerGrid); + + return $header; + }, + + _createBody: function() { + var $content = this._content = $("<tbody>"); + + var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass) + .append($content); + + var $body = this._body = $("<div>").addClass(this.gridBodyClass) + .append($bodyGrid); + + return $body; + }, + + _createPagerContainer: function() { + var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container); + return $(pagerContainer).addClass(this.pagerContainerClass); + }, + + _eachField: function(callBack) { + var self = this; + $.each(this.fields, function(index, field) { + return callBack.call(self, field, index); + }); + }, + + _createHeaderRow: function() { + if($.isFunction(this.headerRowRenderer)) { + return $(this.headerRowRenderer()); + } + + var $result = $("<tr>").addClass(this.headerRowClass); + + this._eachField(function(field, index) { + var $th = $("<th>").addClass(field.headercss || field.css) + .appendTo($result) + .append(field.headerTemplate ? field.headerTemplate() : "") + .css("width", field.width); + + if(this.sorting && field.sorting) { + $th.addClass(this.sortableClass) + .on("click", $.proxy(function() { + this.sort(index); + }, this)); + } + }); + + return $result; + }, + + _createFilterRow: function() { + if($.isFunction(this.filterRowRenderer)) { + return $(this.filterRowRenderer()); + } + + var $result = $("<tr>").addClass(this.filterRowClass); + + this._eachField(function(field) { + $("<td>").addClass(field.css) + .appendTo($result) + .append(field.filterTemplate ? field.filterTemplate() : "") + .width(field.width); + }); + + return $result; + }, + + _createInsertRow: function() { + if($.isFunction(this.insertRowRenderer)) { + return $(this.insertRowRenderer()); + } + + var $result = $("<tr>").addClass(this.insertRowClass); + + this._eachField(function(field) { + $("<td>").addClass(field.css) + .appendTo($result) + .append(field.insertTemplate ? field.insertTemplate() : "") + .width(field.width); + }); + + return $result; + }, + + _callEventHandler: function(handler, eventParams) { + return handler.call(this, $.extend(eventParams, { + grid: this + })); + }, + + reset: function() { + this._resetSorting(); + this._resetPager(); + this.refresh(); + }, + + _resetPager: function() { + this._firstDisplayingPage = 1; + this._setPage(1); + }, + + _resetSorting: function() { + this._sortField = null; + this._sortOrder = SORT_ORDER_ASC; + this._clearSortingCss(); + }, + + refresh: function() { + this._callEventHandler(this.onRefreshing); + + this.cancelEdit(); + + this._refreshHeading(); + this._refreshFiltering(); + this._refreshInserting(); + this._refreshContent(); + this._refreshPager(); + this._refreshSize(); + + this._callEventHandler(this.onRefreshed); + }, + + _refreshHeading: function() { + this._headerRow.toggle(this.heading); + }, + + _refreshFiltering: function() { + this._filterRow.toggle(this.filtering); + }, + + _refreshInserting: function() { + this._insertRow.toggle(this.inserting); + }, + + _refreshContent: function() { + var $content = this._content; + $content.empty(); + + if(!this.data.length) { + $content.append(this._createNoDataRow()); + return this; + } + + var indexFrom = this._loadStrategy.firstDisplayIndex(); + var indexTo = this._loadStrategy.lastDisplayIndex(); + + for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) { + var item = this.data[itemIndex]; + $content.append(this._createRow(item, itemIndex)); + } + }, + + _createNoDataRow: function() { + var noDataContent = getOrApply(this.noDataContent, this); + return $("<tr>").addClass(this.noDataRowClass) + .append($("<td>").attr("colspan", this.fields.length).append(noDataContent)); + }, + + _createNoDataContent: function() { + return $.isFunction(this.noDataRenderer) + ? this.noDataRenderer() + : this.noDataText; + }, + + _createRow: function(item, itemIndex) { + var $result; + + if($.isFunction(this.rowRenderer)) { + $result = $(this.rowRenderer(item, itemIndex)); + } else { + $result = $("<tr>"); + this._renderCells($result, item); + } + + $result.addClass(this._getRowClasses(item, itemIndex)) + .data(JSGRID_ROW_DATA_KEY, item) + .on("click", $.proxy(function(e) { + this.rowClick({ + item: item, + itemIndex: itemIndex, + event: e + }); + }, this)); + +
1,170
Formatting: Reformat jsgrid.core.js
1,170
.js
core
mit
tabalinas/jsgrid
10062819
<NME> jsgrid.core.js <BEF> (function(window, $, undefined) { var JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID, JSGRID_ROW_DATA_KEY = "JSGridItem", JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", SORT_ORDER_ASC = "asc", SORT_ORDER_DESC = "desc", FIRST_PAGE_PLACEHOLDER = "{first}", PAGES_PLACEHOLDER = "{pages}", PREV_PAGE_PLACEHOLDER = "{prev}", NEXT_PAGE_PLACEHOLDER = "{next}", LAST_PAGE_PLACEHOLDER = "{last}", PAGE_INDEX_PLACEHOLDER = "{pageIndex}", PAGE_COUNT_PLACEHOLDER = "{pageCount}", EMPTY_HREF = "javascript:void(0);"; var getOrApply = function(value, context) { if($.isFunction(value)) { return value.apply(context, $.makeArray(arguments).slice(2)); } return value; }; var defaultController = { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }; function Grid(element, config) { var $element = $(element); $element.data(JSGRID_DATA_KEY, this); this._container = $element; this.data = []; this.fields = []; this._editingRow = null; this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._firstDisplayingPage = 1; this._init(config); this.render(); } Grid.prototype = { width: "auto", height: "auto", updateOnResize: true, rowClass: $.noop, rowRenderer: null, rowClick: function(args) { if(this.editing) { this.editItem($(args.event.target).closest("tr")); } }, noDataContent: "Not found", noDataRowClass: "jsgrid-nodata-row", heading: true, headerRowRenderer: null, headerRowClass: "jsgrid-header-row", filtering: false, filterRowRenderer: null, filterRowClass: "jsgrid-filter-row", inserting: false, insertRowRenderer: null, insertRowClass: "jsgrid-insert-row", editing: false, editRowRenderer: null, editRowClass: "jsgrid-edit-row", confirmDeleting: true, deleteConfirm: "Are you sure?", selecting: true, selectedRowClass: "jsgrid-selected-row", oddRowClass: "jsgrid-row", evenRowClass: "jsgrid-alt-row", sorting: false, sortableClass: "jsgrid-header-sortable", sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc", sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc", paging: false, 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: "...", pagerContainerClass: "jsgrid-pager-container", pagerClass: "jsgrid-pager", pagerNavButtonClass: "jsgrid-pager-nav-button", pageClass: "jsgrid-pager-page", currentPageClass: "jsgrid-pager-current-page", pageLoading: false, autoload: false, controller: defaultController, loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, onRefreshing: $.noop, onRefreshed: $.noop, onItemDeleting: $.noop, onItemDeleted: $.noop, onItemInserting: $.noop, onItemInserted: $.noop, onItemUpdating: $.noop, onItemUpdated: $.noop, onDataLoading: $.noop, onDataLoaded: $.noop, onOptionChanging: $.noop, onOptionChanged: $.noop, onError: $.noop, containerClass: "jsgrid", tableClass: "jsgrid-table", gridHeaderClass: "jsgrid-grid-header", gridBodyClass: "jsgrid-grid-body", _init: function(config) { $.extend(this, config); this._initLoadStrategy(); this._initController(); this._initFields(); this._attachWindowLoadResize(); this._attachWindowResizeCallback(); }, loadStrategy: function() { return this.pageLoading ? new jsGrid.loadStrategies.PageLoadingStrategy(this) : new jsGrid.loadStrategies.DirectLoadingStrategy(this); }, _initLoadStrategy: function() { this._loadStrategy = getOrApply(this.loadStrategy, this); }, _initController: function() { this._controller = $.extend({}, defaultController, getOrApply(this.controller, this)); }, loadIndicator: function(config) { return new jsGrid.LoadIndicator(config); }, _initFields: function() { var self = this; self.fields = $.map(self.fields, function(field) { if($.isPlainObject(field)) { var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field; field = new fieldConstructor(field); } field._grid = self; return field; }); }, _attachWindowLoadResize: function() { $(window).on("load", $.proxy(this._refreshSize, this)); }, _attachWindowResizeCallback: function() { if(this.updateOnResize) { $(window).on("resize", $.proxy(this._refreshSize, this)); } }, _detachWindowResizeCallback: function() { $(window).off("resize", this._refreshSize); }, option: function(key, value) { var optionChangingEventArgs, optionChangedEventArgs; if(arguments.length === 1) { return this[key]; } optionChangingEventArgs = { option: key, oldValue: this[key], newValue: value }; this._callEventHandler(this.onOptionChanging, optionChangingEventArgs); this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue); optionChangedEventArgs = { option: optionChangingEventArgs.option, value: optionChangingEventArgs.newValue }; this._callEventHandler(this.onOptionChanged, optionChangedEventArgs); }, _handleOptionChange: function(name, value) { this[name] = value; switch(name) { case "width": case "height": this._refreshSize(); break; case "rowClass": case "rowRenderer": case "rowClick": case "noDataText": case "noDataRowClass": case "noDataContent": case "selecting": case "selectedRowClass": case "oddRowClass": case "evenRowClass": this._refreshContent(); break; case "pageButtonCount": case "pagerFormat": case "pagePrevText": case "pageNextText": case "pageFirstText": case "pageLastText": case "pageNavigatorNextText": case "pageNavigatorPrevText": case "pagerClass": case "pagerNavButtonClass": case "pageClass": case "currentPageClass": this._refreshPager(); break; case "fields": this._initFields(); this.render(); break; case "data": case "editing": case "heading": case "filtering": case "inserting": case "paging": this.refresh(); break; case "pageLoading": this._initLoadStrategy(); this.search(); break; case "pageIndex": this.openPage(value); break; case "pageSize": this.refresh(); this.search(); break; case "editRowRenderer": case "editRowClass": this.cancelEdit(); break; default: this.render(); break; } }, destroy: function() { this._detachWindowResizeCallback(); this._clear(); this._container.removeData(JSGRID_DATA_KEY); }, render: function() { this._clear(); this._container.addClass(this.containerClass) .css("position", "relative") .append(this._createHeader()) .append(this._createBody()); this._pagerContainer = this._createPagerContainer(); this._loadIndicator = this._createLoadIndicator(); this.refresh(); return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); }, _createLoadIndicator: function() { return getOrApply(this.loadIndicator, this, { message: this.loadMessage, shading: this.loadShading, container: this._container }); }, _clear: function() { this.cancelEdit(); clearTimeout(this._loadingTimer); this._pagerContainer && this._pagerContainer.empty(); this._container.empty() .css({ position: "", width: "", height: "" }); }, _createHeader: function() { var $headerRow = this._headerRow = this._createHeaderRow(), $filterRow = this._filterRow = this._createFilterRow(), $insertRow = this._insertRow = this._createInsertRow(); var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass) .append($headerRow) .append($filterRow) .append($insertRow); var $header = this._header = $("<div>").addClass(this.gridHeaderClass) .append($headerGrid); return $header; }, _createBody: function() { var $content = this._content = $("<tbody>"); var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass) .append($content); var $body = this._body = $("<div>").addClass(this.gridBodyClass) .append($bodyGrid); return $body; }, _createPagerContainer: function() { var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container); return $(pagerContainer).addClass(this.pagerContainerClass); }, _eachField: function(callBack) { var self = this; $.each(this.fields, function(index, field) { return callBack.call(self, field, index); }); }, _createHeaderRow: function() { if($.isFunction(this.headerRowRenderer)) { return $(this.headerRowRenderer()); } var $result = $("<tr>").addClass(this.headerRowClass); this._eachField(function(field, index) { var $th = $("<th>").addClass(field.headercss || field.css) .appendTo($result) .append(field.headerTemplate ? field.headerTemplate() : "") .css("width", field.width); if(this.sorting && field.sorting) { $th.addClass(this.sortableClass) .on("click", $.proxy(function() { this.sort(index); }, this)); } }); return $result; }, _createFilterRow: function() { if($.isFunction(this.filterRowRenderer)) { return $(this.filterRowRenderer()); } var $result = $("<tr>").addClass(this.filterRowClass); this._eachField(function(field) { $("<td>").addClass(field.css) .appendTo($result) .append(field.filterTemplate ? field.filterTemplate() : "") .width(field.width); }); return $result; }, _createInsertRow: function() { if($.isFunction(this.insertRowRenderer)) { return $(this.insertRowRenderer()); } var $result = $("<tr>").addClass(this.insertRowClass); this._eachField(function(field) { $("<td>").addClass(field.css) .appendTo($result) .append(field.insertTemplate ? field.insertTemplate() : "") .width(field.width); }); return $result; }, _callEventHandler: function(handler, eventParams) { return handler.call(this, $.extend(eventParams, { grid: this })); }, reset: function() { this._resetSorting(); this._resetPager(); this.refresh(); }, _resetPager: function() { this._firstDisplayingPage = 1; this._setPage(1); }, _resetSorting: function() { this._sortField = null; this._sortOrder = SORT_ORDER_ASC; this._clearSortingCss(); }, refresh: function() { this._callEventHandler(this.onRefreshing); this.cancelEdit(); this._refreshHeading(); this._refreshFiltering(); this._refreshInserting(); this._refreshContent(); this._refreshPager(); this._refreshSize(); this._callEventHandler(this.onRefreshed); }, _refreshHeading: function() { this._headerRow.toggle(this.heading); }, _refreshFiltering: function() { this._filterRow.toggle(this.filtering); }, _refreshInserting: function() { this._insertRow.toggle(this.inserting); }, _refreshContent: function() { var $content = this._content; $content.empty(); if(!this.data.length) { $content.append(this._createNoDataRow()); return this; } var indexFrom = this._loadStrategy.firstDisplayIndex(); var indexTo = this._loadStrategy.lastDisplayIndex(); for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) { var item = this.data[itemIndex]; $content.append(this._createRow(item, itemIndex)); } }, _createNoDataRow: function() { var noDataContent = getOrApply(this.noDataContent, this); return $("<tr>").addClass(this.noDataRowClass) .append($("<td>").attr("colspan", this.fields.length).append(noDataContent)); }, _createNoDataContent: function () { return $.isFunction(this.noDataRenderer) ? this.noDataRenderer() : this.noDataText; }, _createRow: function(item, itemIndex) { var $result; if($.isFunction(this.rowRenderer)) { $result = $(this.rowRenderer(item, itemIndex)); } else { $result = $("<tr>"); this._renderCells($result, item); } $result.addClass(this._getRowClasses(item, itemIndex)) .data(JSGRID_ROW_DATA_KEY, item) .on("click", $.proxy(function(e) { this.rowClick({ item: item, itemIndex: itemIndex, event: e }); }, this)); if(this.selecting) { this._attachRowHover($result); } return $result; }, _getRowClasses: function(item, itemIndex) { var classes = []; classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass); classes.push(getOrApply(this.rowClass, this, item, itemIndex)); return classes.join(" "); }, _attachRowHover: function($row) { var selectedRowClass = this.selectedRowClass; $row.hover(function() { $(this).addClass(selectedRowClass); }, function() { $(this).removeClass(selectedRowClass); } ); }, _renderCells: function($row, item) { this._eachField(function(field) { $row.append(this._createCell(item, field)); }); return this; }, _createCell: function(item, field) { var $result; var fieldValue = item[field.name]; if($.isFunction(field.cellRenderer)) { $result = $(field.cellRenderer(fieldValue, item)); } else { $result = $("<td>").append(field.itemTemplate ? field.itemTemplate(fieldValue, item) : fieldValue); } $result.addClass(field.css) .width(field.width); field.align && $result.addClass("jsgrid-align-" + field.align); return $result; }, sort: function(field, order) { if($.isPlainObject(field)) { order = field.order; field = field.field; } this._clearSortingCss(); this._setSortingParams(field, order); this._setSortingCss(); return this._loadStrategy.sort(); }, _clearSortingCss: function() { this._headerRow.find("th") .removeClass(this.sortAscClass) .removeClass(this.sortDescClass); }, _setSortingParams: function(field, order) { field = this._normalizeSortingField(field); order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC); this._sortField = field; this._sortOrder = order; }, _normalizeSortingField: function(field) { if($.isNumeric(field)) { return this.fields[field]; } if(typeof field === "string") { return $.grep(this.fields, function (f) { return f.name === field; })[0]; } return field; }, _reversedSortOrder: function(order) { return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC); }, _setSortingCss: function() { var fieldIndex = $.inArray(this._sortField, this.fields); this._headerRow.find("th").eq(fieldIndex) .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass); }, _sortData: function() { var sortFactor = this._sortFactor(), sortField = this._sortField; if(sortField) { this.data.sort(function(item1, item2) { return sortFactor * sortField.sortingFunc(item1[sortField.name], item2[sortField.name]); }); } }, _sortFactor: function() { return this._sortOrder === SORT_ORDER_ASC ? 1 : -1; }, _itemsCount: function() { return this._loadStrategy.itemsCount(); }, _pagesCount: function() { var itemsCount = this._itemsCount(), pageSize = this.pageSize; return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0); }, _refreshPager: function() { var $pagerContainer = this._pagerContainer; $pagerContainer.empty(); if(this.paging && this._pagesCount() > 1) { $pagerContainer.show() .append(this._createPager()); } else { $pagerContainer.hide(); } }, _createPager: function() { var pageIndex = this.pageIndex, pageCount = this._pagesCount(), pagerParts = this.pagerFormat.split(" "); pagerParts = $.map(pagerParts, $.proxy(function(pagerPart) { var result = pagerPart; if(pagerPart === PAGES_PLACEHOLDER) { result = this._createPages(); } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) { result = pageIndex > 1 ? this._createPagerNavButton(this.pageFirstText, 1) : ""; } else if(pagerPart === PREV_PAGE_PLACEHOLDER) { result = pageIndex > 1 ? this._createPagerNavButton(this.pagePrevText, pageIndex - 1) : ""; } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) { result = pageIndex < pageCount ? this._createPagerNavButton(this.pageNextText, pageIndex + 1) : ""; } else if(pagerPart === LAST_PAGE_PLACEHOLDER) { result = pageIndex < pageCount ? this._createPagerNavButton(this.pageLastText, pageCount) : ""; } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) { result = pageIndex; } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) { result = pageCount; } return $.isArray(result) ? result.concat([" "]) : [result, " "]; }, this)); var $pager = $("<div>").addClass(this.pagerClass) .append(pagerParts); return $pager; }, _createPages: function() { var pageCount = this._pagesCount(), pageButtonCount = this.pageButtonCount, firstDisplayingPage = this._firstDisplayingPage, pages = [], pageNumber; if(firstDisplayingPage > 1) { pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages)); } for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) { pages.push(pageNumber === this.pageIndex ? this._createPagerCurrentPage() : this._createPagerPage(pageNumber)); } if((firstDisplayingPage + pageButtonCount - 1) < pageCount) { pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages)); } return pages; }, _createPagerNavButton: function(text, pageIndex) { return this._createPagerButton(text, this.pagerNavButtonClass, function() { this.openPage(pageIndex); }); }, _createPagerPageNavButton: function(text, handler) { return this._createPagerButton(text, this.pagerNavButtonClass, handler); }, _createPagerPage: function(pageIndex) { return this._createPagerButton(pageIndex, this.pageClass, function() { this.openPage(pageIndex); }); }, _createPagerButton: function(text, css, handler) { var $link = $("<a>").attr("href", EMPTY_HREF) .html(text) .on("click", $.proxy(handler, this)); return $("<span>").addClass(css).append($link); }, _createPagerCurrentPage: function() { return $("<span>") .addClass(this.pageClass) .addClass(this.currentPageClass) .text(this.pageIndex); }, _refreshSize: function() { this._refreshHeight(); this._refreshWidth(); }, _refreshWidth: function() { var $headerGrid = this._headerGrid, $bodyGrid = this._bodyGrid, width = this.width, scrollBarWidth = this._scrollBarWidth(), gridWidth; if(width === "auto") { $headerGrid.width("auto"); gridWidth = $headerGrid.outerWidth(); width = gridWidth + scrollBarWidth; } $headerGrid.width(""); $bodyGrid.width(""); this._header.css("padding-right", scrollBarWidth); this._container.width(width); gridWidth = $headerGrid.outerWidth(); $bodyGrid.width(gridWidth); }, _scrollBarWidth: (function() { var result; return function() { if(result === undefined) { var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"); var $ghostContent = $("<div style='height:100px;'></div>"); $ghostContainer.append($ghostContent).appendTo("body"); var width = $ghostContent.innerWidth(); $ghostContainer.css("overflow-y", "auto"); var widthExcludingScrollBar = $ghostContent.innerWidth(); $ghostContainer.remove(); result = width - widthExcludingScrollBar; } return result; }; })(), _refreshHeight: function() { var container = this._container, pagerContainer = this._pagerContainer, height = this.height, nonBodyHeight; container.height(height); if(height !== "auto") { height = container.height(); nonBodyHeight = this._header.outerHeight(true); if(pagerContainer.parents(container).length) { nonBodyHeight += pagerContainer.outerHeight(true); } this._body.outerHeight(height - nonBodyHeight); } }, showPrevPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1; this._refreshPager(); }, showNextPages: function() { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount, pageCount = this._pagesCount(); this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount) ? pageCount - pageButtonCount + 1 : firstDisplayingPage + pageButtonCount; this._refreshPager(); }, openPage: function(pageIndex) { if(pageIndex < 1 || pageIndex > this._pagesCount()) return; this._setPage(pageIndex); this._loadStrategy.openPage(pageIndex); }, _setPage: function(pageIndex) { var firstDisplayingPage = this._firstDisplayingPage, pageButtonCount = this.pageButtonCount; this.pageIndex = pageIndex; if(pageIndex < firstDisplayingPage) { this._firstDisplayingPage = pageIndex; } if(pageIndex > firstDisplayingPage + pageButtonCount - 1) { this._firstDisplayingPage = pageIndex - pageButtonCount + 1; } }, _controllerCall: function(method, param, doneCallback) { this._showLoading(); var controller = this._controller; if(!controller || !controller[method]) { throw new Error("controller has no method '" + method + "'"); } return $.when(controller[method](param)) .done($.proxy(doneCallback, this)) .fail($.proxy(this._errorHandler, this)) .always($.proxy(this._hideLoading, this)); }, _errorHandler: function() { this._callEventHandler(this.onError, { args: $.makeArray(arguments) }); }, _showLoading: function() { clearTimeout(this._loadingTimer); this._loadingTimer = setTimeout($.proxy(function() { this._loadIndicator.show(); }, this), this.loadIndicationDelay); }, _hideLoading: function() { clearTimeout(this._loadingTimer); this._loadIndicator.hide(); }, search: function(filter) { this._resetSorting(); this._resetPager(); return this.loadData(filter); }, loadData: function(filter) { filter = filter || (this.filtering ? this._getFilter() : {}); $.extend(filter, this._loadStrategy.loadParams(), this._sortingParams()); this._callEventHandler(this.onDataLoading, { filter: filter }); return this._controllerCall("loadData", filter, function(loadedData) { this._loadStrategy.finishLoad(loadedData); this._callEventHandler(this.onDataLoaded, { data: loadedData }); }); }, _getFilter: function() { var result = {}; this._eachField(function(field) { if(field.filtering) { result[field.name] = field.filterValue(); } }); return result; }, _sortingParams: function() { if(this.sorting && this._sortField) { return { sortField: this._sortField.name, sortOrder: this._sortOrder }; } return {}; }, clearFilter: function() { var $filterRow = this._createFilterRow(); this._filterRow.replaceWith($filterRow); this._filterRow = $filterRow; return this.search(); }, insertItem: function(item) { var insertingItem = item || this._getInsertItem(); this._callEventHandler(this.onItemInserting, { item: insertingItem }); return this._controllerCall("insertItem", insertingItem, function(insertedItem) { insertedItem = insertedItem || insertingItem; this._loadStrategy.finishInsert(insertedItem); this._callEventHandler(this.onItemInserted, { item: insertedItem }); }); }, _getInsertItem: function() { var result = {}; this._eachField(function(field) { if(field.inserting) { result[field.name] = field.insertValue(); } }); return result; }, clearInsert: function() { var insertRow = this._createInsertRow(); this._insertRow.replaceWith(insertRow); this._insertRow = insertRow; this.refresh(); }, editItem: function(item) { var $row = this._rowByItem(item); if($row.length) { this._editRow($row); } }, _rowByItem: function(item) { if(item.jquery || item.nodeType) return $(item); return this._content.find("tr").filter(function() { return $.data(this, JSGRID_ROW_DATA_KEY) === item; }); }, _editRow: function($row) { if(!this.editing) return; if(this._editingRow) { this.cancelEdit(); } var item = $row.data(JSGRID_ROW_DATA_KEY), $editRow = this._createEditRow(item); this._editingRow = $row; $row.hide(); $editRow.insertAfter($row); $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); }, _createEditRow: function(item) { if($.isFunction(this.editRowRenderer)) { return $(this.editRowRenderer(item, this._itemIndex(item))); } var $result = $("<tr>").addClass(this.editRowClass); this._eachField(function(field) { $("<td>").addClass(field.css) .appendTo($result) .append(field.editTemplate ? field.editTemplate(item[field.name], item) : "") .width(field.width || "auto"); }); return $result; }, updateItem: function(item, editedItem) { if(arguments.length === 1) { editedItem = item; } var $row = item ? this._rowByItem(item) : this._editingRow; editedItem = editedItem || this._getEditedItem(); return this._updateRow($row, editedItem); }, _updateRow: function($updatingRow, editedItem) { var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), updatingItemIndex = this._itemIndex(updatingItem); $.extend(updatingItem, editedItem); this._callEventHandler(this.onItemUpdating, { row: $updatingRow, item: updatingItem, itemIndex: updatingItemIndex }); return this._controllerCall("updateItem", updatingItem, function(updatedItem) { updatedItem = updatedItem || updatingItem; this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); this._callEventHandler(this.onItemUpdated, { row: $updatingRow, item: updatedItem, itemIndex: updatingItemIndex }); }); }, _itemIndex: function(item) { return $.inArray(item, this.data); }, _finishUpdate: function($updatedRow, updatedItem, updatedItemIndex) { this.cancelEdit(); this.data[updatedItemIndex] = updatedItem; $updatedRow.replaceWith(this._createRow(updatedItem, updatedItemIndex)); }, _getEditedItem: function() { var result = {}; this._eachField(function(field) { if(field.editing) { result[field.name] = field.editValue(); } }); return result; }, cancelEdit: function() { if(!this._editingRow) { return; } var $row = this._editingRow, $editRow = $row.data(JSGRID_EDIT_ROW_DATA_KEY); $editRow.remove(); $row.show(); this._editingRow = null; }, deleteItem: function(item) { var $row = this._rowByItem(item); if(!$row.length) return; if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); }, _deleteRow: function($row) { var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), deletingItemIndex = this._itemIndex(deletingItem); this._callEventHandler(this.onItemDeleting, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); return this._controllerCall("deleteItem", deletingItem, function() { this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); this._callEventHandler(this.onItemDeleted, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); }); } }; $.fn.jsGrid = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSGRID_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance.render(); } } else { new Grid($element, config); } }); return result; }; window.jsGrid = { Grid: Grid, fields: [] }; }(window, jQuery)); var result = []; Object.keys(item).forEach(function(key,index) { var entry = ""; //Fields.length is greater than 0 when we are matching agaisnt fields //Field.length will be 0 when exporting header rows if (fields.length > 0){ var field = fields[index]; //Field may be excluded from data export if ("includeInDataExport" in field){ if (field.includeInDataExport){ //Field may be a select, which requires additional logic if (field.type === "select"){ var selectedItem = getItem(item, field); var resultItem = $.grep(field.items, function(item, index) { return item[field.valueField] === selectedItem; })[0] || ""; entry = resultItem[field.textField]; } else{ entry = getItem(item, field); } } else{ return; } } else{ entry = getItem(item, field); } if (transforms.hasOwnProperty(field.name)){ entry = transforms[field.name](entry); } } else{ entry = item[key]; } if (encapsulate){ entry = '"'+entry+'"'; } result.push(entry); }); return result.join(delimiter) + newline; }, getFilter: function() { var result = {}; this._eachField(function(field) { if(field.filtering) { this._setItemFieldValue(result, field, field.filterValue()); } }); return result; }, _sortingParams: function() { if(this.sorting && this._sortField) { return { sortField: this._sortField.name, sortOrder: this._sortOrder }; } return {}; }, getSorting: function() { var sortingParams = this._sortingParams(); return { field: sortingParams.sortField, order: sortingParams.sortOrder }; }, clearFilter: function() { var $filterRow = this._createFilterRow(); this._filterRow.replaceWith($filterRow); this._filterRow = $filterRow; return this.search(); }, insertItem: function(item) { var insertingItem = item || this._getValidatedInsertItem(); if(!insertingItem) return $.Deferred().reject().promise(); var args = this._callEventHandler(this.onItemInserting, { item: insertingItem }); return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) { insertedItem = insertedItem || insertingItem; this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation); this._callEventHandler(this.onItemInserted, { item: insertedItem }); }); }, _getValidatedInsertItem: function() { var item = this._getInsertItem(); return this._validateItem(item, this._insertRow) ? item : null; }, _getInsertItem: function() { var result = {}; this._eachField(function(field) { if(field.inserting) { this._setItemFieldValue(result, field, field.insertValue()); } }); return result; }, _validateItem: function(item, $row) { var validationErrors = []; var args = { item: item, itemIndex: this._rowIndex($row), row: $row }; this._eachField(function(field) { if(!field.validate || ($row === this._insertRow && !field.inserting) || ($row === this._getEditRow() && !field.editing)) return; var fieldValue = this._getItemFieldValue(item, field); var errors = this._validation.validate($.extend({ value: fieldValue, rules: field.validate }, args)); this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors); if(!errors.length) return; validationErrors.push.apply(validationErrors, $.map(errors, function(message) { return { field: field, message: message }; })); }); if(!validationErrors.length) return true; var invalidArgs = $.extend({ errors: validationErrors }, args); this._callEventHandler(this.onItemInvalid, invalidArgs); this.invalidNotify(invalidArgs); return false; }, _setCellValidity: function($cell, errors) { $cell .toggleClass(this.invalidClass, !!errors.length) .attr("title", errors.join("\n")); }, clearInsert: function() { var insertRow = this._createInsertRow(); this._insertRow.replaceWith(insertRow); this._insertRow = insertRow; this.refresh(); }, editItem: function(item) { var $row = this.rowByItem(item); if($row.length) { this._editRow($row); } }, rowByItem: function(item) { if(item.jquery || item.nodeType) return $(item); return this._content.find("tr").filter(function() { return $.data(this, JSGRID_ROW_DATA_KEY) === item; }); }, _editRow: function($row) { if(!this.editing) return; var item = $row.data(JSGRID_ROW_DATA_KEY); var args = this._callEventHandler(this.onItemEditing, { row: $row, item: item, itemIndex: this._itemIndex(item) }); if(args.cancel) return; if(this._editingRow) { this.cancelEdit(); } var $editRow = this._createEditRow(item); this._editingRow = $row; $row.hide(); $editRow.insertBefore($row); $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); }, _createEditRow: function(item) { if($.isFunction(this.editRowRenderer)) { return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) })); } var $result = $("<tr>").addClass(this.editRowClass); this._eachField(function(field) { var fieldValue = this._getItemFieldValue(item, field); this._prepareCell("<td>", field, "editcss") .append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item })) .appendTo($result); }); return $result; }, updateItem: function(item, editedItem) { if(arguments.length === 1) { editedItem = item; } var $row = item ? this.rowByItem(item) : this._editingRow; editedItem = editedItem || this._getValidatedEditedItem(); if(!editedItem) return; return this._updateRow($row, editedItem); }, _getValidatedEditedItem: function() { var item = this._getEditedItem(); return this._validateItem(item, this._getEditRow()) ? item : null; }, _updateRow: function($updatingRow, editedItem) { var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), updatingItemIndex = this._itemIndex(updatingItem), updatedItem = $.extend(true, {}, updatingItem, editedItem); var args = this._callEventHandler(this.onItemUpdating, { row: $updatingRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: updatingItem }); return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) { var previousItem = $.extend(true, {}, updatingItem); updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem); var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); this._callEventHandler(this.onItemUpdated, { row: $updatedRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: previousItem }); }); }, _rowIndex: function(row) { return this._content.children().index($(row)); }, _itemIndex: function(item) { return $.inArray(item, this.data); }, _finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) { this.cancelEdit(); this.data[updatedItemIndex] = updatedItem; var $updatedRow = this._createRow(updatedItem, updatedItemIndex); $updatingRow.replaceWith($updatedRow); return $updatedRow; }, _getEditedItem: function() { var result = {}; this._eachField(function(field) { if(field.editing) { this._setItemFieldValue(result, field, field.editValue()); } }); return result; }, cancelEdit: function() { if(!this._editingRow) return; var $row = this._editingRow, editingItem = $row.data(JSGRID_ROW_DATA_KEY), editingItemIndex = this._itemIndex(editingItem); this._callEventHandler(this.onItemEditCancelling, { row: $row, item: editingItem, itemIndex: editingItemIndex }); this._getEditRow().remove(); this._editingRow.show(); this._editingRow = null; }, _getEditRow: function() { return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY); }, deleteItem: function(item) { var $row = this.rowByItem(item); if(!$row.length) return; if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); }, _deleteRow: function($row) { var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), deletingItemIndex = this._itemIndex(deletingItem); var args = this._callEventHandler(this.onItemDeleting, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); return this._controllerCall("deleteItem", deletingItem, args.cancel, function() { this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); this._callEventHandler(this.onItemDeleted, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); }); } }; $.fn.jsGrid = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSGRID_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance.render(); } } else { new Grid($element, config); } }); return result; }; var fields = {}; var setDefaults = function(config) { var componentPrototype; if($.isPlainObject(config)) { componentPrototype = Grid.prototype; } else { componentPrototype = fields[config].prototype; config = arguments[1] || {}; } $.extend(componentPrototype, config); }; var locales = {}; var locale = function(lang) { var localeConfig = $.isPlainObject(lang) ? lang : locales[lang]; if(!localeConfig) throw Error("unknown locale " + lang); setLocale(jsGrid, localeConfig); }; var setLocale = function(obj, localeConfig) { $.each(localeConfig, function(field, value) { if($.isPlainObject(value)) { setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value); return; } if(obj.hasOwnProperty(field)) { obj[field] = value; } else { obj.prototype[field] = value; } }); }; window.jsGrid = { Grid: Grid, fields: fields, setDefaults: setDefaults, locales: locales, locale: locale, version: "@VERSION" }; }(window, jQuery)); <MSG> Formatting: Reformat jsgrid.core.js <DFF> @@ -1,1170 +1,1170 @@ -(function(window, $, undefined) { - - var JSGRID = "JSGrid", - JSGRID_DATA_KEY = JSGRID, - JSGRID_ROW_DATA_KEY = "JSGridItem", - JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", - - SORT_ORDER_ASC = "asc", - SORT_ORDER_DESC = "desc", - - FIRST_PAGE_PLACEHOLDER = "{first}", - PAGES_PLACEHOLDER = "{pages}", - PREV_PAGE_PLACEHOLDER = "{prev}", - NEXT_PAGE_PLACEHOLDER = "{next}", - LAST_PAGE_PLACEHOLDER = "{last}", - PAGE_INDEX_PLACEHOLDER = "{pageIndex}", - PAGE_COUNT_PLACEHOLDER = "{pageCount}", - - EMPTY_HREF = "javascript:void(0);"; - - var getOrApply = function(value, context) { - if($.isFunction(value)) { - return value.apply(context, $.makeArray(arguments).slice(2)); - } - return value; - }; - - var defaultController = { - loadData: $.noop, - insertItem: $.noop, - updateItem: $.noop, - deleteItem: $.noop - }; - - - function Grid(element, config) { - var $element = $(element); - - $element.data(JSGRID_DATA_KEY, this); - - this._container = $element; - - this.data = []; - this.fields = []; - - this._editingRow = null; - this._sortField = null; - this._sortOrder = SORT_ORDER_ASC; - this._firstDisplayingPage = 1; - - this._init(config); - this.render(); - } - - Grid.prototype = { - width: "auto", - height: "auto", - updateOnResize: true, - - rowClass: $.noop, - rowRenderer: null, - - rowClick: function(args) { - if(this.editing) { - this.editItem($(args.event.target).closest("tr")); - } - }, - - noDataContent: "Not found", - noDataRowClass: "jsgrid-nodata-row", - - heading: true, - headerRowRenderer: null, - headerRowClass: "jsgrid-header-row", - - filtering: false, - filterRowRenderer: null, - filterRowClass: "jsgrid-filter-row", - - inserting: false, - insertRowRenderer: null, - insertRowClass: "jsgrid-insert-row", - - editing: false, - editRowRenderer: null, - editRowClass: "jsgrid-edit-row", - - confirmDeleting: true, - deleteConfirm: "Are you sure?", - - selecting: true, - selectedRowClass: "jsgrid-selected-row", - oddRowClass: "jsgrid-row", - evenRowClass: "jsgrid-alt-row", - - sorting: false, - sortableClass: "jsgrid-header-sortable", - sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc", - sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc", - - paging: false, - 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: "...", - pagerContainerClass: "jsgrid-pager-container", - pagerClass: "jsgrid-pager", - pagerNavButtonClass: "jsgrid-pager-nav-button", - pageClass: "jsgrid-pager-page", - currentPageClass: "jsgrid-pager-current-page", - - pageLoading: false, - - autoload: false, - controller: defaultController, - - loadIndication: true, - loadIndicationDelay: 500, - loadMessage: "Please, wait...", - loadShading: true, - - onRefreshing: $.noop, - onRefreshed: $.noop, - onItemDeleting: $.noop, - onItemDeleted: $.noop, - onItemInserting: $.noop, - onItemInserted: $.noop, - onItemUpdating: $.noop, - onItemUpdated: $.noop, - onDataLoading: $.noop, - onDataLoaded: $.noop, - onOptionChanging: $.noop, - onOptionChanged: $.noop, - onError: $.noop, - - containerClass: "jsgrid", - tableClass: "jsgrid-table", - gridHeaderClass: "jsgrid-grid-header", - gridBodyClass: "jsgrid-grid-body", - - _init: function(config) { - $.extend(this, config); - this._initLoadStrategy(); - this._initController(); - this._initFields(); - this._attachWindowLoadResize(); - this._attachWindowResizeCallback(); - }, - - loadStrategy: function() { - return this.pageLoading - ? new jsGrid.loadStrategies.PageLoadingStrategy(this) - : new jsGrid.loadStrategies.DirectLoadingStrategy(this); - }, - - _initLoadStrategy: function() { - this._loadStrategy = getOrApply(this.loadStrategy, this); - }, - - _initController: function() { - this._controller = $.extend({}, defaultController, getOrApply(this.controller, this)); - }, - - loadIndicator: function(config) { - return new jsGrid.LoadIndicator(config); - }, - - _initFields: function() { - var self = this; - self.fields = $.map(self.fields, function(field) { - if($.isPlainObject(field)) { - var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field; - field = new fieldConstructor(field); - } - field._grid = self; - return field; - }); - }, - - _attachWindowLoadResize: function() { - $(window).on("load", $.proxy(this._refreshSize, this)); - }, - - _attachWindowResizeCallback: function() { - if(this.updateOnResize) { - $(window).on("resize", $.proxy(this._refreshSize, this)); - } - }, - - _detachWindowResizeCallback: function() { - $(window).off("resize", this._refreshSize); - }, - - option: function(key, value) { - var optionChangingEventArgs, - optionChangedEventArgs; - - if(arguments.length === 1) { - return this[key]; - } - - optionChangingEventArgs = { - option: key, - oldValue: this[key], - newValue: value - }; - this._callEventHandler(this.onOptionChanging, optionChangingEventArgs); - - this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue); - - optionChangedEventArgs = { - option: optionChangingEventArgs.option, - value: optionChangingEventArgs.newValue - }; - this._callEventHandler(this.onOptionChanged, optionChangedEventArgs); - }, - - _handleOptionChange: function(name, value) { - this[name] = value; - - switch(name) { - case "width": - case "height": - this._refreshSize(); - break; - case "rowClass": - case "rowRenderer": - case "rowClick": - case "noDataText": - case "noDataRowClass": - case "noDataContent": - case "selecting": - case "selectedRowClass": - case "oddRowClass": - case "evenRowClass": - this._refreshContent(); - break; - case "pageButtonCount": - case "pagerFormat": - case "pagePrevText": - case "pageNextText": - case "pageFirstText": - case "pageLastText": - case "pageNavigatorNextText": - case "pageNavigatorPrevText": - case "pagerClass": - case "pagerNavButtonClass": - case "pageClass": - case "currentPageClass": - this._refreshPager(); - break; - case "fields": - this._initFields(); - this.render(); - break; - case "data": - case "editing": - case "heading": - case "filtering": - case "inserting": - case "paging": - this.refresh(); - break; - case "pageLoading": - this._initLoadStrategy(); - this.search(); - break; - case "pageIndex": - this.openPage(value); - break; - case "pageSize": - this.refresh(); - this.search(); - break; - case "editRowRenderer": - case "editRowClass": - this.cancelEdit(); - break; - default: - this.render(); - break; - } - }, - - destroy: function() { - this._detachWindowResizeCallback(); - this._clear(); - this._container.removeData(JSGRID_DATA_KEY); - }, - - render: function() { - this._clear(); - - this._container.addClass(this.containerClass) - .css("position", "relative") - .append(this._createHeader()) - .append(this._createBody()); - - this._pagerContainer = this._createPagerContainer(); - this._loadIndicator = this._createLoadIndicator(); - - this.refresh(); - - return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); - }, - - _createLoadIndicator: function() { - return getOrApply(this.loadIndicator, this, { - message: this.loadMessage, - shading: this.loadShading, - container: this._container - }); - }, - - _clear: function() { - this.cancelEdit(); - - clearTimeout(this._loadingTimer); - - this._pagerContainer && this._pagerContainer.empty(); - - this._container.empty() - .css({ position: "", width: "", height: "" }); - }, - - _createHeader: function() { - var $headerRow = this._headerRow = this._createHeaderRow(), - $filterRow = this._filterRow = this._createFilterRow(), - $insertRow = this._insertRow = this._createInsertRow(); - - var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass) - .append($headerRow) - .append($filterRow) - .append($insertRow); - - var $header = this._header = $("<div>").addClass(this.gridHeaderClass) - .append($headerGrid); - - return $header; - }, - - _createBody: function() { - var $content = this._content = $("<tbody>"); - - var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass) - .append($content); - - var $body = this._body = $("<div>").addClass(this.gridBodyClass) - .append($bodyGrid); - - return $body; - }, - - _createPagerContainer: function() { - var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container); - return $(pagerContainer).addClass(this.pagerContainerClass); - }, - - _eachField: function(callBack) { - var self = this; - $.each(this.fields, function(index, field) { - return callBack.call(self, field, index); - }); - }, - - _createHeaderRow: function() { - if($.isFunction(this.headerRowRenderer)) { - return $(this.headerRowRenderer()); - } - - var $result = $("<tr>").addClass(this.headerRowClass); - - this._eachField(function(field, index) { - var $th = $("<th>").addClass(field.headercss || field.css) - .appendTo($result) - .append(field.headerTemplate ? field.headerTemplate() : "") - .css("width", field.width); - - if(this.sorting && field.sorting) { - $th.addClass(this.sortableClass) - .on("click", $.proxy(function() { - this.sort(index); - }, this)); - } - }); - - return $result; - }, - - _createFilterRow: function() { - if($.isFunction(this.filterRowRenderer)) { - return $(this.filterRowRenderer()); - } - - var $result = $("<tr>").addClass(this.filterRowClass); - - this._eachField(function(field) { - $("<td>").addClass(field.css) - .appendTo($result) - .append(field.filterTemplate ? field.filterTemplate() : "") - .width(field.width); - }); - - return $result; - }, - - _createInsertRow: function() { - if($.isFunction(this.insertRowRenderer)) { - return $(this.insertRowRenderer()); - } - - var $result = $("<tr>").addClass(this.insertRowClass); - - this._eachField(function(field) { - $("<td>").addClass(field.css) - .appendTo($result) - .append(field.insertTemplate ? field.insertTemplate() : "") - .width(field.width); - }); - - return $result; - }, - - _callEventHandler: function(handler, eventParams) { - return handler.call(this, $.extend(eventParams, { - grid: this - })); - }, - - reset: function() { - this._resetSorting(); - this._resetPager(); - this.refresh(); - }, - - _resetPager: function() { - this._firstDisplayingPage = 1; - this._setPage(1); - }, - - _resetSorting: function() { - this._sortField = null; - this._sortOrder = SORT_ORDER_ASC; - this._clearSortingCss(); - }, - - refresh: function() { - this._callEventHandler(this.onRefreshing); - - this.cancelEdit(); - - this._refreshHeading(); - this._refreshFiltering(); - this._refreshInserting(); - this._refreshContent(); - this._refreshPager(); - this._refreshSize(); - - this._callEventHandler(this.onRefreshed); - }, - - _refreshHeading: function() { - this._headerRow.toggle(this.heading); - }, - - _refreshFiltering: function() { - this._filterRow.toggle(this.filtering); - }, - - _refreshInserting: function() { - this._insertRow.toggle(this.inserting); - }, - - _refreshContent: function() { - var $content = this._content; - $content.empty(); - - if(!this.data.length) { - $content.append(this._createNoDataRow()); - return this; - } - - var indexFrom = this._loadStrategy.firstDisplayIndex(); - var indexTo = this._loadStrategy.lastDisplayIndex(); - - for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) { - var item = this.data[itemIndex]; - $content.append(this._createRow(item, itemIndex)); - } - }, - - _createNoDataRow: function() { - var noDataContent = getOrApply(this.noDataContent, this); - return $("<tr>").addClass(this.noDataRowClass) - .append($("<td>").attr("colspan", this.fields.length).append(noDataContent)); - }, - - _createNoDataContent: function () { - return $.isFunction(this.noDataRenderer) - ? this.noDataRenderer() - : this.noDataText; - }, - - _createRow: function(item, itemIndex) { - var $result; - - if($.isFunction(this.rowRenderer)) { - $result = $(this.rowRenderer(item, itemIndex)); - } else { - $result = $("<tr>"); - this._renderCells($result, item); - } - - $result.addClass(this._getRowClasses(item, itemIndex)) - .data(JSGRID_ROW_DATA_KEY, item) - .on("click", $.proxy(function(e) { - this.rowClick({ - item: item, - itemIndex: itemIndex, - event: e - }); - }, this)); - - if(this.selecting) { - this._attachRowHover($result); - } - - return $result; - }, - - _getRowClasses: function(item, itemIndex) { - var classes = []; - classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass); - classes.push(getOrApply(this.rowClass, this, item, itemIndex)); - return classes.join(" "); - }, - - _attachRowHover: function($row) { - var selectedRowClass = this.selectedRowClass; - $row.hover(function() { - $(this).addClass(selectedRowClass); - }, - function() { - $(this).removeClass(selectedRowClass); - } - ); - }, - - _renderCells: function($row, item) { - this._eachField(function(field) { - $row.append(this._createCell(item, field)); - }); - return this; - }, - - _createCell: function(item, field) { - var $result; - var fieldValue = item[field.name]; - - if($.isFunction(field.cellRenderer)) { - $result = $(field.cellRenderer(fieldValue, item)); - } else { - $result = $("<td>").append(field.itemTemplate ? field.itemTemplate(fieldValue, item) : fieldValue); - } - - $result.addClass(field.css) - .width(field.width); - - field.align && $result.addClass("jsgrid-align-" + field.align); - - return $result; - }, - - sort: function(field, order) { - if($.isPlainObject(field)) { - order = field.order; - field = field.field; - } - - this._clearSortingCss(); - this._setSortingParams(field, order); - this._setSortingCss(); - return this._loadStrategy.sort(); - }, - - _clearSortingCss: function() { - this._headerRow.find("th") - .removeClass(this.sortAscClass) - .removeClass(this.sortDescClass); - }, - - _setSortingParams: function(field, order) { - field = this._normalizeSortingField(field); - order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC); - - this._sortField = field; - this._sortOrder = order; - }, - - _normalizeSortingField: function(field) { - if($.isNumeric(field)) { - return this.fields[field]; - } - - if(typeof field === "string") { - return $.grep(this.fields, function (f) { - return f.name === field; - })[0]; - } - - return field; - }, - - _reversedSortOrder: function(order) { - return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC); - }, - - _setSortingCss: function() { - var fieldIndex = $.inArray(this._sortField, this.fields); - - this._headerRow.find("th").eq(fieldIndex) - .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass); - }, - - _sortData: function() { - var sortFactor = this._sortFactor(), - sortField = this._sortField; - - if(sortField) { - this.data.sort(function(item1, item2) { - return sortFactor * sortField.sortingFunc(item1[sortField.name], item2[sortField.name]); - }); - } - }, - - _sortFactor: function() { - return this._sortOrder === SORT_ORDER_ASC ? 1 : -1; - }, - - _itemsCount: function() { - return this._loadStrategy.itemsCount(); - }, - - _pagesCount: function() { - var itemsCount = this._itemsCount(), - pageSize = this.pageSize; - return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0); - }, - - _refreshPager: function() { - var $pagerContainer = this._pagerContainer; - $pagerContainer.empty(); - - if(this.paging && this._pagesCount() > 1) { - $pagerContainer.show() - .append(this._createPager()); - } else { - $pagerContainer.hide(); - } - }, - - _createPager: function() { - var pageIndex = this.pageIndex, - pageCount = this._pagesCount(), - pagerParts = this.pagerFormat.split(" "); - - pagerParts = $.map(pagerParts, $.proxy(function(pagerPart) { - var result = pagerPart; - - if(pagerPart === PAGES_PLACEHOLDER) { - result = this._createPages(); - } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) { - result = pageIndex > 1 ? this._createPagerNavButton(this.pageFirstText, 1) : ""; - } else if(pagerPart === PREV_PAGE_PLACEHOLDER) { - result = pageIndex > 1 ? this._createPagerNavButton(this.pagePrevText, pageIndex - 1) : ""; - } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) { - result = pageIndex < pageCount ? this._createPagerNavButton(this.pageNextText, pageIndex + 1) : ""; - } else if(pagerPart === LAST_PAGE_PLACEHOLDER) { - result = pageIndex < pageCount ? this._createPagerNavButton(this.pageLastText, pageCount) : ""; - } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) { - result = pageIndex; - } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) { - result = pageCount; - } - - return $.isArray(result) ? result.concat([" "]) : [result, " "]; - }, this)); - - var $pager = $("<div>").addClass(this.pagerClass) - .append(pagerParts); - - return $pager; - }, - - _createPages: function() { - var pageCount = this._pagesCount(), - pageButtonCount = this.pageButtonCount, - firstDisplayingPage = this._firstDisplayingPage, - pages = [], - pageNumber; - - if(firstDisplayingPage > 1) { - pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages)); - } - - for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) { - pages.push(pageNumber === this.pageIndex - ? this._createPagerCurrentPage() - : this._createPagerPage(pageNumber)); - } - - if((firstDisplayingPage + pageButtonCount - 1) < pageCount) { - pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages)); - } - - return pages; - }, - - _createPagerNavButton: function(text, pageIndex) { - return this._createPagerButton(text, this.pagerNavButtonClass, function() { - this.openPage(pageIndex); - }); - }, - - _createPagerPageNavButton: function(text, handler) { - return this._createPagerButton(text, this.pagerNavButtonClass, handler); - }, - - _createPagerPage: function(pageIndex) { - return this._createPagerButton(pageIndex, this.pageClass, function() { - this.openPage(pageIndex); - }); - }, - - _createPagerButton: function(text, css, handler) { - var $link = $("<a>").attr("href", EMPTY_HREF) - .html(text) - .on("click", $.proxy(handler, this)); - - return $("<span>").addClass(css).append($link); - }, - - _createPagerCurrentPage: function() { - return $("<span>") - .addClass(this.pageClass) - .addClass(this.currentPageClass) - .text(this.pageIndex); - }, - - _refreshSize: function() { - this._refreshHeight(); - this._refreshWidth(); - }, - - _refreshWidth: function() { - var $headerGrid = this._headerGrid, - $bodyGrid = this._bodyGrid, - width = this.width, - scrollBarWidth = this._scrollBarWidth(), - gridWidth; - - if(width === "auto") { - $headerGrid.width("auto"); - gridWidth = $headerGrid.outerWidth(); - width = gridWidth + scrollBarWidth; - } - - $headerGrid.width(""); - $bodyGrid.width(""); - this._header.css("padding-right", scrollBarWidth); - this._container.width(width); - gridWidth = $headerGrid.outerWidth(); - $bodyGrid.width(gridWidth); - }, - - _scrollBarWidth: (function() { - var result; - - return function() { - if(result === undefined) { - var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"); - var $ghostContent = $("<div style='height:100px;'></div>"); - $ghostContainer.append($ghostContent).appendTo("body"); - var width = $ghostContent.innerWidth(); - $ghostContainer.css("overflow-y", "auto"); - var widthExcludingScrollBar = $ghostContent.innerWidth(); - $ghostContainer.remove(); - result = width - widthExcludingScrollBar; - } - return result; - }; - })(), - - _refreshHeight: function() { - var container = this._container, - pagerContainer = this._pagerContainer, - height = this.height, - nonBodyHeight; - - container.height(height); - - if(height !== "auto") { - height = container.height(); - - nonBodyHeight = this._header.outerHeight(true); - if(pagerContainer.parents(container).length) { - nonBodyHeight += pagerContainer.outerHeight(true); - } - - this._body.outerHeight(height - nonBodyHeight); - } - }, - - showPrevPages: function() { - var firstDisplayingPage = this._firstDisplayingPage, - pageButtonCount = this.pageButtonCount; - - this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1; - - this._refreshPager(); - }, - - showNextPages: function() { - var firstDisplayingPage = this._firstDisplayingPage, - pageButtonCount = this.pageButtonCount, - pageCount = this._pagesCount(); - - this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount) - ? pageCount - pageButtonCount + 1 - : firstDisplayingPage + pageButtonCount; - - this._refreshPager(); - }, - - openPage: function(pageIndex) { - if(pageIndex < 1 || pageIndex > this._pagesCount()) - return; - - this._setPage(pageIndex); - this._loadStrategy.openPage(pageIndex); - }, - - _setPage: function(pageIndex) { - var firstDisplayingPage = this._firstDisplayingPage, - pageButtonCount = this.pageButtonCount; - - this.pageIndex = pageIndex; - - if(pageIndex < firstDisplayingPage) { - this._firstDisplayingPage = pageIndex; - } - - if(pageIndex > firstDisplayingPage + pageButtonCount - 1) { - this._firstDisplayingPage = pageIndex - pageButtonCount + 1; - } - }, - - _controllerCall: function(method, param, doneCallback) { - this._showLoading(); - - var controller = this._controller; - if(!controller || !controller[method]) { - throw new Error("controller has no method '" + method + "'"); - } - - return $.when(controller[method](param)) - .done($.proxy(doneCallback, this)) - .fail($.proxy(this._errorHandler, this)) - .always($.proxy(this._hideLoading, this)); - }, - - _errorHandler: function() { - this._callEventHandler(this.onError, { - args: $.makeArray(arguments) - }); - }, - - _showLoading: function() { - clearTimeout(this._loadingTimer); - - this._loadingTimer = setTimeout($.proxy(function() { - this._loadIndicator.show(); - }, this), this.loadIndicationDelay); - }, - - _hideLoading: function() { - clearTimeout(this._loadingTimer); - this._loadIndicator.hide(); - }, - - search: function(filter) { - this._resetSorting(); - this._resetPager(); - return this.loadData(filter); - }, - - loadData: function(filter) { - filter = filter || (this.filtering ? this._getFilter() : {}); - - $.extend(filter, this._loadStrategy.loadParams(), this._sortingParams()); - - this._callEventHandler(this.onDataLoading, { - filter: filter - }); - - return this._controllerCall("loadData", filter, function(loadedData) { - this._loadStrategy.finishLoad(loadedData); - - this._callEventHandler(this.onDataLoaded, { - data: loadedData - }); - }); - }, - - _getFilter: function() { - var result = {}; - this._eachField(function(field) { - if(field.filtering) { - result[field.name] = field.filterValue(); - } - }); - return result; - }, - - _sortingParams: function() { - if(this.sorting && this._sortField) { - return { - sortField: this._sortField.name, - sortOrder: this._sortOrder - }; - } - return {}; - }, - - clearFilter: function() { - var $filterRow = this._createFilterRow(); - this._filterRow.replaceWith($filterRow); - this._filterRow = $filterRow; - return this.search(); - }, - - insertItem: function(item) { - var insertingItem = item || this._getInsertItem(); - - this._callEventHandler(this.onItemInserting, { - item: insertingItem - }); - - return this._controllerCall("insertItem", insertingItem, function(insertedItem) { - insertedItem = insertedItem || insertingItem; - this._loadStrategy.finishInsert(insertedItem); - - this._callEventHandler(this.onItemInserted, { - item: insertedItem - }); - }); - }, - - _getInsertItem: function() { - var result = {}; - this._eachField(function(field) { - if(field.inserting) { - result[field.name] = field.insertValue(); - } - }); - return result; - }, - - clearInsert: function() { - var insertRow = this._createInsertRow(); - this._insertRow.replaceWith(insertRow); - this._insertRow = insertRow; - this.refresh(); - }, - - editItem: function(item) { - var $row = this._rowByItem(item); - if($row.length) { - this._editRow($row); - } - }, - - _rowByItem: function(item) { - if(item.jquery || item.nodeType) - return $(item); - - return this._content.find("tr").filter(function() { - return $.data(this, JSGRID_ROW_DATA_KEY) === item; - }); - }, - - _editRow: function($row) { - if(!this.editing) - return; - - if(this._editingRow) { - this.cancelEdit(); - } - - var item = $row.data(JSGRID_ROW_DATA_KEY), - $editRow = this._createEditRow(item); - - this._editingRow = $row; - $row.hide(); - $editRow.insertAfter($row); - $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); - }, - - _createEditRow: function(item) { - if($.isFunction(this.editRowRenderer)) { - return $(this.editRowRenderer(item, this._itemIndex(item))); - } - - var $result = $("<tr>").addClass(this.editRowClass); - - this._eachField(function(field) { - $("<td>").addClass(field.css) - .appendTo($result) - .append(field.editTemplate ? field.editTemplate(item[field.name], item) : "") - .width(field.width || "auto"); - }); - - return $result; - }, - - updateItem: function(item, editedItem) { - if(arguments.length === 1) { - editedItem = item; - } - - var $row = item ? this._rowByItem(item) : this._editingRow; - editedItem = editedItem || this._getEditedItem(); - - return this._updateRow($row, editedItem); - }, - - _updateRow: function($updatingRow, editedItem) { - var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), - updatingItemIndex = this._itemIndex(updatingItem); - - $.extend(updatingItem, editedItem); - - this._callEventHandler(this.onItemUpdating, { - row: $updatingRow, - item: updatingItem, - itemIndex: updatingItemIndex - }); - - return this._controllerCall("updateItem", updatingItem, function(updatedItem) { - updatedItem = updatedItem || updatingItem; - this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); - - this._callEventHandler(this.onItemUpdated, { - row: $updatingRow, - item: updatedItem, - itemIndex: updatingItemIndex - }); - }); - }, - - _itemIndex: function(item) { - return $.inArray(item, this.data); - }, - - _finishUpdate: function($updatedRow, updatedItem, updatedItemIndex) { - this.cancelEdit(); - this.data[updatedItemIndex] = updatedItem; - $updatedRow.replaceWith(this._createRow(updatedItem, updatedItemIndex)); - }, - - _getEditedItem: function() { - var result = {}; - this._eachField(function(field) { - if(field.editing) { - result[field.name] = field.editValue(); - } - }); - return result; - }, - - cancelEdit: function() { - if(!this._editingRow) { - return; - } - - var $row = this._editingRow, - $editRow = $row.data(JSGRID_EDIT_ROW_DATA_KEY); - - $editRow.remove(); - $row.show(); - this._editingRow = null; - }, - - deleteItem: function(item) { - var $row = this._rowByItem(item); - - if(!$row.length) - return; - - if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) - return; - - return this._deleteRow($row); - }, - - _deleteRow: function($row) { - var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), - deletingItemIndex = this._itemIndex(deletingItem); - - this._callEventHandler(this.onItemDeleting, { - row: $row, - item: deletingItem, - itemIndex: deletingItemIndex - }); - - return this._controllerCall("deleteItem", deletingItem, function() { - this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); - - this._callEventHandler(this.onItemDeleted, { - row: $row, - item: deletingItem, - itemIndex: deletingItemIndex - }); - }); - } - }; - - $.fn.jsGrid = function(config) { - var args = $.makeArray(arguments), - methodArgs = args.slice(1), - result = this; - - this.each(function() { - var $element = $(this), - instance = $element.data(JSGRID_DATA_KEY), - methodResult; - - if(instance) { - if(typeof config === "string") { - methodResult = instance[config].apply(instance, methodArgs); - if(methodResult !== undefined && methodResult !== instance) { - result = methodResult; - return false; - } - } else { - instance._detachWindowResizeCallback(); - instance._init(config); - instance.render(); - } - } else { - new Grid($element, config); - } - }); - - return result; - }; - - window.jsGrid = { - Grid: Grid, - fields: [] - }; - -}(window, jQuery)); \ No newline at end of file +(function(window, $, undefined) { + + var JSGRID = "JSGrid", + JSGRID_DATA_KEY = JSGRID, + JSGRID_ROW_DATA_KEY = "JSGridItem", + JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", + + SORT_ORDER_ASC = "asc", + SORT_ORDER_DESC = "desc", + + FIRST_PAGE_PLACEHOLDER = "{first}", + PAGES_PLACEHOLDER = "{pages}", + PREV_PAGE_PLACEHOLDER = "{prev}", + NEXT_PAGE_PLACEHOLDER = "{next}", + LAST_PAGE_PLACEHOLDER = "{last}", + PAGE_INDEX_PLACEHOLDER = "{pageIndex}", + PAGE_COUNT_PLACEHOLDER = "{pageCount}", + + EMPTY_HREF = "javascript:void(0);"; + + var getOrApply = function(value, context) { + if($.isFunction(value)) { + return value.apply(context, $.makeArray(arguments).slice(2)); + } + return value; + }; + + var defaultController = { + loadData: $.noop, + insertItem: $.noop, + updateItem: $.noop, + deleteItem: $.noop + }; + + + function Grid(element, config) { + var $element = $(element); + + $element.data(JSGRID_DATA_KEY, this); + + this._container = $element; + + this.data = []; + this.fields = []; + + this._editingRow = null; + this._sortField = null; + this._sortOrder = SORT_ORDER_ASC; + this._firstDisplayingPage = 1; + + this._init(config); + this.render(); + } + + Grid.prototype = { + width: "auto", + height: "auto", + updateOnResize: true, + + rowClass: $.noop, + rowRenderer: null, + + rowClick: function(args) { + if(this.editing) { + this.editItem($(args.event.target).closest("tr")); + } + }, + + noDataContent: "Not found", + noDataRowClass: "jsgrid-nodata-row", + + heading: true, + headerRowRenderer: null, + headerRowClass: "jsgrid-header-row", + + filtering: false, + filterRowRenderer: null, + filterRowClass: "jsgrid-filter-row", + + inserting: false, + insertRowRenderer: null, + insertRowClass: "jsgrid-insert-row", + + editing: false, + editRowRenderer: null, + editRowClass: "jsgrid-edit-row", + + confirmDeleting: true, + deleteConfirm: "Are you sure?", + + selecting: true, + selectedRowClass: "jsgrid-selected-row", + oddRowClass: "jsgrid-row", + evenRowClass: "jsgrid-alt-row", + + sorting: false, + sortableClass: "jsgrid-header-sortable", + sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc", + sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc", + + paging: false, + 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: "...", + pagerContainerClass: "jsgrid-pager-container", + pagerClass: "jsgrid-pager", + pagerNavButtonClass: "jsgrid-pager-nav-button", + pageClass: "jsgrid-pager-page", + currentPageClass: "jsgrid-pager-current-page", + + pageLoading: false, + + autoload: false, + controller: defaultController, + + loadIndication: true, + loadIndicationDelay: 500, + loadMessage: "Please, wait...", + loadShading: true, + + onRefreshing: $.noop, + onRefreshed: $.noop, + onItemDeleting: $.noop, + onItemDeleted: $.noop, + onItemInserting: $.noop, + onItemInserted: $.noop, + onItemUpdating: $.noop, + onItemUpdated: $.noop, + onDataLoading: $.noop, + onDataLoaded: $.noop, + onOptionChanging: $.noop, + onOptionChanged: $.noop, + onError: $.noop, + + containerClass: "jsgrid", + tableClass: "jsgrid-table", + gridHeaderClass: "jsgrid-grid-header", + gridBodyClass: "jsgrid-grid-body", + + _init: function(config) { + $.extend(this, config); + this._initLoadStrategy(); + this._initController(); + this._initFields(); + this._attachWindowLoadResize(); + this._attachWindowResizeCallback(); + }, + + loadStrategy: function() { + return this.pageLoading + ? new jsGrid.loadStrategies.PageLoadingStrategy(this) + : new jsGrid.loadStrategies.DirectLoadingStrategy(this); + }, + + _initLoadStrategy: function() { + this._loadStrategy = getOrApply(this.loadStrategy, this); + }, + + _initController: function() { + this._controller = $.extend({}, defaultController, getOrApply(this.controller, this)); + }, + + loadIndicator: function(config) { + return new jsGrid.LoadIndicator(config); + }, + + _initFields: function() { + var self = this; + self.fields = $.map(self.fields, function(field) { + if($.isPlainObject(field)) { + var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field; + field = new fieldConstructor(field); + } + field._grid = self; + return field; + }); + }, + + _attachWindowLoadResize: function() { + $(window).on("load", $.proxy(this._refreshSize, this)); + }, + + _attachWindowResizeCallback: function() { + if(this.updateOnResize) { + $(window).on("resize", $.proxy(this._refreshSize, this)); + } + }, + + _detachWindowResizeCallback: function() { + $(window).off("resize", this._refreshSize); + }, + + option: function(key, value) { + var optionChangingEventArgs, + optionChangedEventArgs; + + if(arguments.length === 1) { + return this[key]; + } + + optionChangingEventArgs = { + option: key, + oldValue: this[key], + newValue: value + }; + this._callEventHandler(this.onOptionChanging, optionChangingEventArgs); + + this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue); + + optionChangedEventArgs = { + option: optionChangingEventArgs.option, + value: optionChangingEventArgs.newValue + }; + this._callEventHandler(this.onOptionChanged, optionChangedEventArgs); + }, + + _handleOptionChange: function(name, value) { + this[name] = value; + + switch(name) { + case "width": + case "height": + this._refreshSize(); + break; + case "rowClass": + case "rowRenderer": + case "rowClick": + case "noDataText": + case "noDataRowClass": + case "noDataContent": + case "selecting": + case "selectedRowClass": + case "oddRowClass": + case "evenRowClass": + this._refreshContent(); + break; + case "pageButtonCount": + case "pagerFormat": + case "pagePrevText": + case "pageNextText": + case "pageFirstText": + case "pageLastText": + case "pageNavigatorNextText": + case "pageNavigatorPrevText": + case "pagerClass": + case "pagerNavButtonClass": + case "pageClass": + case "currentPageClass": + this._refreshPager(); + break; + case "fields": + this._initFields(); + this.render(); + break; + case "data": + case "editing": + case "heading": + case "filtering": + case "inserting": + case "paging": + this.refresh(); + break; + case "pageLoading": + this._initLoadStrategy(); + this.search(); + break; + case "pageIndex": + this.openPage(value); + break; + case "pageSize": + this.refresh(); + this.search(); + break; + case "editRowRenderer": + case "editRowClass": + this.cancelEdit(); + break; + default: + this.render(); + break; + } + }, + + destroy: function() { + this._detachWindowResizeCallback(); + this._clear(); + this._container.removeData(JSGRID_DATA_KEY); + }, + + render: function() { + this._clear(); + + this._container.addClass(this.containerClass) + .css("position", "relative") + .append(this._createHeader()) + .append(this._createBody()); + + this._pagerContainer = this._createPagerContainer(); + this._loadIndicator = this._createLoadIndicator(); + + this.refresh(); + + return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); + }, + + _createLoadIndicator: function() { + return getOrApply(this.loadIndicator, this, { + message: this.loadMessage, + shading: this.loadShading, + container: this._container + }); + }, + + _clear: function() { + this.cancelEdit(); + + clearTimeout(this._loadingTimer); + + this._pagerContainer && this._pagerContainer.empty(); + + this._container.empty() + .css({ position: "", width: "", height: "" }); + }, + + _createHeader: function() { + var $headerRow = this._headerRow = this._createHeaderRow(), + $filterRow = this._filterRow = this._createFilterRow(), + $insertRow = this._insertRow = this._createInsertRow(); + + var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass) + .append($headerRow) + .append($filterRow) + .append($insertRow); + + var $header = this._header = $("<div>").addClass(this.gridHeaderClass) + .append($headerGrid); + + return $header; + }, + + _createBody: function() { + var $content = this._content = $("<tbody>"); + + var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass) + .append($content); + + var $body = this._body = $("<div>").addClass(this.gridBodyClass) + .append($bodyGrid); + + return $body; + }, + + _createPagerContainer: function() { + var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container); + return $(pagerContainer).addClass(this.pagerContainerClass); + }, + + _eachField: function(callBack) { + var self = this; + $.each(this.fields, function(index, field) { + return callBack.call(self, field, index); + }); + }, + + _createHeaderRow: function() { + if($.isFunction(this.headerRowRenderer)) { + return $(this.headerRowRenderer()); + } + + var $result = $("<tr>").addClass(this.headerRowClass); + + this._eachField(function(field, index) { + var $th = $("<th>").addClass(field.headercss || field.css) + .appendTo($result) + .append(field.headerTemplate ? field.headerTemplate() : "") + .css("width", field.width); + + if(this.sorting && field.sorting) { + $th.addClass(this.sortableClass) + .on("click", $.proxy(function() { + this.sort(index); + }, this)); + } + }); + + return $result; + }, + + _createFilterRow: function() { + if($.isFunction(this.filterRowRenderer)) { + return $(this.filterRowRenderer()); + } + + var $result = $("<tr>").addClass(this.filterRowClass); + + this._eachField(function(field) { + $("<td>").addClass(field.css) + .appendTo($result) + .append(field.filterTemplate ? field.filterTemplate() : "") + .width(field.width); + }); + + return $result; + }, + + _createInsertRow: function() { + if($.isFunction(this.insertRowRenderer)) { + return $(this.insertRowRenderer()); + } + + var $result = $("<tr>").addClass(this.insertRowClass); + + this._eachField(function(field) { + $("<td>").addClass(field.css) + .appendTo($result) + .append(field.insertTemplate ? field.insertTemplate() : "") + .width(field.width); + }); + + return $result; + }, + + _callEventHandler: function(handler, eventParams) { + return handler.call(this, $.extend(eventParams, { + grid: this + })); + }, + + reset: function() { + this._resetSorting(); + this._resetPager(); + this.refresh(); + }, + + _resetPager: function() { + this._firstDisplayingPage = 1; + this._setPage(1); + }, + + _resetSorting: function() { + this._sortField = null; + this._sortOrder = SORT_ORDER_ASC; + this._clearSortingCss(); + }, + + refresh: function() { + this._callEventHandler(this.onRefreshing); + + this.cancelEdit(); + + this._refreshHeading(); + this._refreshFiltering(); + this._refreshInserting(); + this._refreshContent(); + this._refreshPager(); + this._refreshSize(); + + this._callEventHandler(this.onRefreshed); + }, + + _refreshHeading: function() { + this._headerRow.toggle(this.heading); + }, + + _refreshFiltering: function() { + this._filterRow.toggle(this.filtering); + }, + + _refreshInserting: function() { + this._insertRow.toggle(this.inserting); + }, + + _refreshContent: function() { + var $content = this._content; + $content.empty(); + + if(!this.data.length) { + $content.append(this._createNoDataRow()); + return this; + } + + var indexFrom = this._loadStrategy.firstDisplayIndex(); + var indexTo = this._loadStrategy.lastDisplayIndex(); + + for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) { + var item = this.data[itemIndex]; + $content.append(this._createRow(item, itemIndex)); + } + }, + + _createNoDataRow: function() { + var noDataContent = getOrApply(this.noDataContent, this); + return $("<tr>").addClass(this.noDataRowClass) + .append($("<td>").attr("colspan", this.fields.length).append(noDataContent)); + }, + + _createNoDataContent: function() { + return $.isFunction(this.noDataRenderer) + ? this.noDataRenderer() + : this.noDataText; + }, + + _createRow: function(item, itemIndex) { + var $result; + + if($.isFunction(this.rowRenderer)) { + $result = $(this.rowRenderer(item, itemIndex)); + } else { + $result = $("<tr>"); + this._renderCells($result, item); + } + + $result.addClass(this._getRowClasses(item, itemIndex)) + .data(JSGRID_ROW_DATA_KEY, item) + .on("click", $.proxy(function(e) { + this.rowClick({ + item: item, + itemIndex: itemIndex, + event: e + }); + }, this)); + +
1,170
Formatting: Reformat jsgrid.core.js
1,170
.js
core
mit
tabalinas/jsgrid
10062820
<NME> jsgrid.field.select.js <BEF> (function(jsGrid, $, undefined) { var NumberField = jsGrid.NumberField; var numberValueType = "number"; var stringValueType = "string"; function SelectField(config) { this.items = []; this.selectedIndex = -1; this.valueField = ""; this.textField = ""; if(config.valueField && config.items.length) { var firstItemValue = config.items[0][config.valueField]; this.valueType = (typeof firstItemValue) === numberValueType ? numberValueType : stringValueType; } this.sorter = this.valueType; NumberField.call(this, config); } SelectField.prototype = new NumberField({ align: "center", valueType: numberValueType, itemTemplate: function(value) { var items = this.items, valueField = this.valueField, textField = this.textField, resultItem; if(valueField) { resultItem = $.grep(items, function(item, index) { return item[valueField] === value; })[0] || {}; } else { resultItem = items[value]; } var result = (textField ? resultItem[textField] : resultItem); return (result === undefined || result === null) ? "" : result; }, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createSelect(); if(this.autosearch) { $result.on("change", function(e) { grid.search(); }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createSelect(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createSelect(); (value !== undefined) && $result.val(value); return $result; }, filterValue: function() { var val = this.filterControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, insertValue: function() { var val = this.insertControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, editValue: function() { var val = this.editControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, _createSelect: function() { var $result = $("<select>"), valueField = this.valueField, textField = this.textField, selectedIndex = this.selectedIndex; $.each(this.items, function(index, item) { var value = valueField ? item[valueField] : index, text = textField ? item[textField] : item; var $option = $("<option>") .attr("value", value) .text(text) .appendTo($result); $option.prop("selected", (selectedIndex === index)); }); $result.prop("disabled", !!this.readOnly); return $result; } }); jsGrid.fields.select = jsGrid.SelectField = SelectField; }(jsGrid, jQuery)); <MSG> Merge pull request #631 from richraid21/master Fields: Allow for -1 selectedIndex assignments in the select field <DFF> @@ -107,11 +107,11 @@ .text(text) .appendTo($result); - $option.prop("selected", (selectedIndex === index)); }); $result.prop("disabled", !!this.readOnly); - + $result.prop("selectedIndex", selectedIndex); + return $result; } });
2
Merge pull request #631 from richraid21/master
2
.js
field
mit
tabalinas/jsgrid
10062821
<NME> jsgrid.field.select.js <BEF> (function(jsGrid, $, undefined) { var NumberField = jsGrid.NumberField; var numberValueType = "number"; var stringValueType = "string"; function SelectField(config) { this.items = []; this.selectedIndex = -1; this.valueField = ""; this.textField = ""; if(config.valueField && config.items.length) { var firstItemValue = config.items[0][config.valueField]; this.valueType = (typeof firstItemValue) === numberValueType ? numberValueType : stringValueType; } this.sorter = this.valueType; NumberField.call(this, config); } SelectField.prototype = new NumberField({ align: "center", valueType: numberValueType, itemTemplate: function(value) { var items = this.items, valueField = this.valueField, textField = this.textField, resultItem; if(valueField) { resultItem = $.grep(items, function(item, index) { return item[valueField] === value; })[0] || {}; } else { resultItem = items[value]; } var result = (textField ? resultItem[textField] : resultItem); return (result === undefined || result === null) ? "" : result; }, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createSelect(); if(this.autosearch) { $result.on("change", function(e) { grid.search(); }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createSelect(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createSelect(); (value !== undefined) && $result.val(value); return $result; }, filterValue: function() { var val = this.filterControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, insertValue: function() { var val = this.insertControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, editValue: function() { var val = this.editControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, _createSelect: function() { var $result = $("<select>"), valueField = this.valueField, textField = this.textField, selectedIndex = this.selectedIndex; $.each(this.items, function(index, item) { var value = valueField ? item[valueField] : index, text = textField ? item[textField] : item; var $option = $("<option>") .attr("value", value) .text(text) .appendTo($result); $option.prop("selected", (selectedIndex === index)); }); $result.prop("disabled", !!this.readOnly); return $result; } }); jsGrid.fields.select = jsGrid.SelectField = SelectField; }(jsGrid, jQuery)); <MSG> Merge pull request #631 from richraid21/master Fields: Allow for -1 selectedIndex assignments in the select field <DFF> @@ -107,11 +107,11 @@ .text(text) .appendTo($result); - $option.prop("selected", (selectedIndex === index)); }); $result.prop("disabled", !!this.readOnly); - + $result.prop("selectedIndex", selectedIndex); + return $result; } });
2
Merge pull request #631 from richraid21/master
2
.js
field
mit
tabalinas/jsgrid
10062822
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062823
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062824
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062825
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062826
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062827
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062828
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062829
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062830
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062831
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062832
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062833
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062834
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062835
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062836
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Merge branch 'master' into fix-long-lines-support <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Merge branch 'master' into fix-long-lines-support
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062837
<NME> README.md <BEF> # Lumen Passport [![Build Status](https://travis-ci.org/dusterio/lumen-passport.svg)](https://travis-ci.org/dusterio/lumen-passport) [![Code Climate](https://codeclimate.com/github/dusterio/lumen-passport/badges/gpa.svg)](https://codeclimate.com/github/dusterio/lumen-passport/badges) [![Total Downloads](https://poser.pugx.org/dusterio/lumen-passport/d/total.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![Latest Stable Version](https://poser.pugx.org/dusterio/lumen-passport/v/stable.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![Latest Unstable Version](https://poser.pugx.org/dusterio/lumen-passport/v/unstable.svg)](https://packagist.org/packages/dusterio/lumen-passport) [![License](https://poser.pugx.org/dusterio/lumen-passport/license.svg)](https://packagist.org/packages/dusterio/lumen-passport) > Making Laravel Passport work with Lumen ## Introduction It's a simple service provider that makes **Laravel Passport** work with **Lumen**. ## Installation First install [Lumen Micro-Framework](https://github.com/laravel/lumen) if you don't have it yet. Then install **Lumen Passport**: ```bash composer require dusterio/lumen-passport ``` Or if you prefer, edit `composer.json` manually and run then `composer update`: ```json { "require": { "dusterio/lumen-passport": "^0.3.5" } } ``` ### Modify the bootstrap flow We need to enable both **Laravel Passport** provider and **Lumen Passport** specific provider: ```php /** @file bootstrap/app.php */ // Enable Facades $app->withFacades(); // Enable Eloquent $app->withEloquent(); // Enable auth middleware (shipped with Lumen) $app->routeMiddleware([ 'auth' => App\Http\Middleware\Authenticate::class, ]); // Register two service providers, Laravel Passport and Lumen adapter $app->register(Laravel\Passport\PassportServiceProvider::class); $app->register(Dusterio\LumenPassport\PassportServiceProvider::class); ``` ### Laravel Passport ^7.3.2 and newer On 30 Jul 2019 [Laravel Passport 7.3.2](https://github.com/laravel/passport/releases/tag/v7.3.2) had a breaking change - new method introduced on Application class that exists in Laravel but not in Lumen. You could either lock in to an older version or swap the Application class like follows: ```php /** @file bootstrap/app.php */ //$app = new Laravel\Lumen\Application( // dirname(__DIR__) //); $app = new \Dusterio\LumenPassport\Lumen7Application( dirname(__DIR__) ); ``` \* _Note: If you look inside this class - all it does is adding an extra method `configurationIsCached()` that always returns `false`._ ### Migrate and install Laravel Passport ```bash # Create new tables for Passport php artisan migrate # Install encryption keys and other stuff for Passport php artisan passport:install ``` It will output the Personal access client ID and secret, and the Password grand client ID and secret. \* _Note: Save the secrets in a safe place, you'll need them later to request the access tokens._ ## Configuration ### Configure Authentication Edit `config/auth.php` to suit your needs. A simple example: ```php /** @file config/auth.php */ return [ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => \App\Models\User::class ] ], ]; ``` \* _Note: Lumen 7.x and older uses `\App\User::class`_ Load the config since Lumen doesn't load config files automatically: ```php /** @file bootstrap/app.php */ $app->configure('auth'); ``` ### Registering Routes Next, you should call the `LumenPassport::routes` method within the `boot` method of your application (one of your service providers). This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens: ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens: ```php Dusterio\LumenPassport\LumenPassport::routes($this->app); ``` You can add that into an existing group, or add use this route registrar independently like so; ```php Dusterio\LumenPassport\LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']); ``` ## User model ```php /** @file app/Models/User.php */ use Laravel\Passport\HasApiTokens; class User extends Model implements AuthenticatableContract, AuthorizableContract { use HasApiTokens, Authenticatable, Authorizable, HasFactory; /* rest of the model */ } ``` ## Usage You'll find all the documentation in [Laravel Passport Docs](https://laravel.com/docs/master/passport). ### Curl example with username and password authentication First you have to [issue an access token](https://laravel.com/docs/master/passport#issuing-access-tokens) and then you can use it to authenticate your requests. ```bash # Request curl --location --request POST '{{APP_URL}}/oauth/token' \ --header 'Content-Type: application/json' \ --data-raw '{ "grant_type": "password", "client_id": "{{CLIENT_ID}}", "client_secret": "{{CLIENT_SECRET}}", "username": "{{USER_EMAIL}}", "password": "{{USER_PASSWORD}}", "scope": "*" }' ``` ```json { "token_type": "Bearer", "expires_in": 31536000, "access_token": "******", "refresh_token": "******" } ``` And with the `access_token` you can request access to the routes that uses the Auth:Api Middleware provided by the **Lumen Passport**. ```php /** @file routes/web.php */ $router->get('/ping', ['middleware' => 'auth', fn () => 'pong']); ``` ```bash # Request curl --location --request GET '{{APP_URL}}/ping' \ --header 'Authorization: Bearer {{ACCESS_TOKEN}}' ``` ```html pong ``` ### Installed routes This package mounts the following routes after you call `routes()` method, all of them belongs to the namespace `\Laravel\Passport\Http\Controllers`: Verb | Path | Controller | Action | Middleware --- | --- | --- | --- | --- POST | /oauth/token | AccessTokenController | issueToken | - GET | /oauth/tokens | AuthorizedAccessTokenController | forUser | auth DELETE | /oauth/tokens/{token_id} | AuthorizedAccessTokenController | destroy | auth POST | /oauth/token/refresh | TransientTokenController | refresh | auth GET | /oauth/clients | ClientController | forUser | auth POST | /oauth/clients | ClientController | store | auth PUT | /oauth/clients/{client_id} | ClientController | update | auth DELETE | /oauth/clients/{client_id} | ClientController | destroy | auth GET | /oauth/scopes | ScopeController | all | auth GET | /oauth/personal-access-tokens | PersonalAccessTokenController | forUser | auth POST | /oauth/personal-access-tokens | PersonalAccessTokenController | store | auth DELETE | /oauth/personal-access-tokens/{token_id} | PersonalAccessTokenController | destroy | auth \* _Note: some of the **Laravel Passport**'s routes had to 'go away' because they are web-related and rely on sessions (eg. authorise pages). Lumen is an API framework so only API-related routes are present._ ## Extra features There are a couple of extra features that aren't present in **Laravel Passport** ### Prefixing Routes You can add that into an existing group, or add use this route registrar independently like so; ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']); /* rest of boot */ } } ``` ### Multiple tokens per client Sometimes it's handy to allow multiple access tokens per password grant client. Eg. user logs in from several browsers simultaneously. Currently **Laravel Passport** does not allow that. ```php /** @file app/Providers/AuthServiceProvider.php */ use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); LumenPassport::allowMultipleTokens(); /* rest of boot */ } } ``` ### Different TTLs for different password clients **Laravel Passport** allows to set one global TTL (time to live) for access tokens, but it may be useful sometimes to set different TTLs for different clients (eg. mobile users get more time than desktop users). Simply do the following in your service provider: ```php /** @file app/Providers/AuthServiceProvider.php */ use Carbon\Carbon; use Dusterio\LumenPassport\LumenPassport; class AuthServiceProvider extends ServiceProvider { public function boot() { LumenPassport::routes($this->app); $client_id = '1'; LumenPassport::tokensExpireIn(Carbon::now()->addDays(14), $client_id); /* rest of boot */ } } ``` If you don't specify client Id, it will simply fall back to Laravel Passport implementation. ### Purge expired tokens ```bash php artisan passport:purge ``` Simply run it to remove expired refresh tokens and their corresponding access tokens from the database. ## Error and issue resolution Instead of opening a new issue, please see if someone has already had it and it has been resolved. If you have found a bug or want to contribute to improving the package, please review the [Contributing guide](https://github.com/dusterio/lumen-passport/blob/master/CONTRIBUTING.md) and the [Code of Conduct](https://github.com/dusterio/lumen-passport/blob/master/CODE_OF_CONDUCT.md). ## Video tutorials I've just started a educational YouTube channel [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg) that will cover top IT trends in software development and DevOps. Also I'm happy to announce my newest tool – [GrammarCI](https://www.grammarci.com/), an automated (as a part of CI/CD process) spelling and grammar checks for your code so that your users don't see your typos :) ## License The MIT License (MIT) Copyright (c) 2016 Denis Mysenko 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. <MSG> Updated README Registering Routes example Updated example with a backslash in front of call to the routes method, as it won't call the correct function otherwise. Like so: \Dusterio\LumenPassport\LumenPassport::routes() <DFF> @@ -131,13 +131,13 @@ Next, you should call the LumenPassport::routes method within the boot method of This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens: ```php -Dusterio\LumenPassport\LumenPassport::routes($this->app); +\Dusterio\LumenPassport\LumenPassport::routes($this->app); ``` You can add that into an existing group, or add use this route registrar independently like so; ```php -Dusterio\LumenPassport\LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']); +\Dusterio\LumenPassport\LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']); ``` ## User model
2
Updated README Registering Routes example
2
.md
md
mit
dusterio/lumen-passport
10062838
<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
10062839
<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
10062840
<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
10062841
<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
10062842
<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
10062843
<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
10062844
<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
10062845
<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
10062846
<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
10062847
<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
10062848
<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
10062849
<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