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
10063450
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.type == string.Empty) { continue; } var themeRules = _theme.Match(token.type); var lineOffset = _document.GetLineByNumber(lineNumber).Offset; _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed missing scopes in tokens <DFF> @@ -87,12 +87,17 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.type == string.Empty) + if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } - var themeRules = _theme.Match(token.type); + var themeRules = new List<ThemeTrieElementRule>(); + + foreach (string scope in token.scopes) + { + themeRules.AddRange(_theme.Match(scope)); + } var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
7
Fixed missing scopes in tokens
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063451
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.type == string.Empty) { continue; } var themeRules = _theme.Match(token.type); var lineOffset = _document.GetLineByNumber(lineNumber).Offset; _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed missing scopes in tokens <DFF> @@ -87,12 +87,17 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.type == string.Empty) + if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } - var themeRules = _theme.Match(token.type); + var themeRules = new List<ThemeTrieElementRule>(); + + foreach (string scope in token.scopes) + { + themeRules.AddRange(_theme.Match(scope)); + } var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
7
Fixed missing scopes in tokens
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063452
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.type == string.Empty) { continue; } var themeRules = _theme.Match(token.type); var lineOffset = _document.GetLineByNumber(lineNumber).Offset; _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed missing scopes in tokens <DFF> @@ -87,12 +87,17 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.type == string.Empty) + if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } - var themeRules = _theme.Match(token.type); + var themeRules = new List<ThemeTrieElementRule>(); + + foreach (string scope in token.scopes) + { + themeRules.AddRange(_theme.Match(scope)); + } var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
7
Fixed missing scopes in tokens
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063453
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.type == string.Empty) { continue; } var themeRules = _theme.Match(token.type); var lineOffset = _document.GetLineByNumber(lineNumber).Offset; _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed missing scopes in tokens <DFF> @@ -87,12 +87,17 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.type == string.Empty) + if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } - var themeRules = _theme.Match(token.type); + var themeRules = new List<ThemeTrieElementRule>(); + + foreach (string scope in token.scopes) + { + themeRules.AddRange(_theme.Match(scope)); + } var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
7
Fixed missing scopes in tokens
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063454
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.type == string.Empty) { continue; } var themeRules = _theme.Match(token.type); var lineOffset = _document.GetLineByNumber(lineNumber).Offset; _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed missing scopes in tokens <DFF> @@ -87,12 +87,17 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.type == string.Empty) + if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } - var themeRules = _theme.Match(token.type); + var themeRules = new List<ThemeTrieElementRule>(); + + foreach (string scope in token.scopes) + { + themeRules.AddRange(_theme.Match(scope)); + } var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
7
Fixed missing scopes in tokens
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063455
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.type == string.Empty) { continue; } var themeRules = _theme.Match(token.type); var lineOffset = _document.GetLineByNumber(lineNumber).Offset; _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed missing scopes in tokens <DFF> @@ -87,12 +87,17 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.type == string.Empty) + if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } - var themeRules = _theme.Match(token.type); + var themeRules = new List<ThemeTrieElementRule>(); + + foreach (string scope in token.scopes) + { + themeRules.AddRange(_theme.Match(scope)); + } var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
7
Fixed missing scopes in tokens
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063456
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.type == string.Empty) { continue; } var themeRules = _theme.Match(token.type); var lineOffset = _document.GetLineByNumber(lineNumber).Offset; _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed missing scopes in tokens <DFF> @@ -87,12 +87,17 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.type == string.Empty) + if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } - var themeRules = _theme.Match(token.type); + var themeRules = new List<ThemeTrieElementRule>(); + + foreach (string scope in token.scopes) + { + themeRules.AddRange(_theme.Match(scope)); + } var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
7
Fixed missing scopes in tokens
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063457
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.type == string.Empty) { continue; } var themeRules = _theme.Match(token.type); var lineOffset = _document.GetLineByNumber(lineNumber).Offset; _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed missing scopes in tokens <DFF> @@ -87,12 +87,17 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.type == string.Empty) + if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } - var themeRules = _theme.Match(token.type); + var themeRules = new List<ThemeTrieElementRule>(); + + foreach (string scope in token.scopes) + { + themeRules.AddRange(_theme.Match(scope)); + } var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
7
Fixed missing scopes in tokens
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063458
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.type == string.Empty) { continue; } var themeRules = _theme.Match(token.type); var lineOffset = _document.GetLineByNumber(lineNumber).Offset; _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed missing scopes in tokens <DFF> @@ -87,12 +87,17 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.type == string.Empty) + if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } - var themeRules = _theme.Match(token.type); + var themeRules = new List<ThemeTrieElementRule>(); + + foreach (string scope in token.scopes) + { + themeRules.AddRange(_theme.Match(scope)); + } var lineOffset = _document.GetLineByNumber(lineNumber).Offset;
7
Fixed missing scopes in tokens
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063459
<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": { } ``` ### Add it in the bootstrap flow ```php // Add in your bootstrap/app.php $app->register(Dusterio\LumenPassport\PassportServiceProvider::class); ``` ### Installed routes Adding this service provider, will mount the following routes: //$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 { public function boot() { LumenPassport::routes($this->app); /* rest of boot */ } } ``` ### User model Make sure your user model uses **Laravel Passport**'s `HasApiTokens` trait. ```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> Update README.md <DFF> @@ -31,13 +31,35 @@ Or add it to `composer.json` manually: } ``` -### Add it in the bootstrap flow +### Modify the bootstrap flow (```bootstrap/app.php``` file) ```php -// Add in your 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, +]); + +// Finally register two service providers - original one and Lumen adapter +$app->register(Laravel\Passport\PassportServiceProvider::class); $app->register(Dusterio\LumenPassport\PassportServiceProvider::class); ``` +### Migrate and install Laravel Passport + +```bash +# Create new tables for Passport +php artisan migrate + +# Install encryption keys and other necessary stuff for Passport +php artisan passport:install +``` + ### Installed routes Adding this service provider, will mount the following routes:
24
Update README.md
2
.md
md
mit
dusterio/lumen-passport
10063460
<NME> setup.js <BEF> ADDFILE <MSG> Setup tests <DFF> @@ -0,0 +1,5 @@ + +/** + * Templates + */ +
5
Setup tests
0
.js
js
mit
ftlabs/fruitmachine
10063461
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063462
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063463
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063464
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063465
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063466
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063467
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063468
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063469
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063470
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063471
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063472
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063473
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063474
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063475
<NME> TextEditor.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:Editing="clr-namespace:AvaloniaEdit.Editing;assembly=AvaloniaEdit"> <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer" VerticalScrollBarVisibility="{TemplateBinding VerticalScrollBarVisibility}" HorizontalScrollBarVisibility="{TemplateBinding HorizontalScrollBarVisibility}" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Padding="{TemplateBinding Padding}" /> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> Merge pull request #145 from BAndysc/master Fix background color in template <DFF> @@ -4,7 +4,8 @@ <Style Selector="AvalonEdit|TextEditor"> <Setter Property="Template"> <ControlTemplate> - <Border BorderBrush="{TemplateBinding BorderBrush}" + <Border Background="{TemplateBinding Background}" + BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Focusable="False" Name="PART_ScrollViewer"
2
Merge pull request #145 from BAndysc/master
1
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063476
<NME> .travis.yml <BEF> script: - "npm test" - "npm coveralls" language: node_js - "8" sudo: false <MSG> Proper npm runnning <DFF> @@ -1,6 +1,6 @@ script: - "npm test" - - "npm coveralls" + - "npm run coveralls" language: node_js
1
Proper npm runnning
1
.yml
travis
mit
ftlabs/fruitmachine
10063477
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063478
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063479
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063480
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063481
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063482
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063483
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063484
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063485
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063486
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063487
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063488
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063489
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063490
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063491
<NME> pascal.tmLanguage.json <BEF> ADDFILE <MSG> textmate: added pascal highlighting <DFF> @@ -0,0 +1,779 @@ +{ + "information_for_contributors": [ + "This file has been converted from https://raw.githubusercontent.com/AnsonYeung/vscode-pascal-language-basics/master/syntaxes/pascal.tmLanguage.yaml", + "If you want to provide a fix or improvement, please create a pull request against the original repository.", + "Once accepted there, we are happy to receive an update request." + ], + "version": "https://github.com/AnsonYeung/vscode-pascal-language-basics/commit/5faf4d487e08fb410f19b23562f9a3cd01f4d86b", + "name": "Pascal", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#program" + }, + { + "include": "#unit" + }, + { + "include": "#interface" + }, + { + "include": "#implementation" + }, + { + "include": "#unit-main" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#asm" + }, + { + "name": "meta.program.end.pascal", + "match": "(?i)\\b(end)\\s*\\.", + "captures": { + "1": { + "name": "keyword.control.pascal" + } + } + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + }, + { + "include": "#keywords" + } + ], + "repository": { + "comment": { + "patterns": [ + { + "name": "comment.block.pascal", + "begin": "\\(\\*", + "end": "\\*\\)" + }, + { + "name": "comment.block.pascal", + "begin": "\\{", + "end": "\\}" + }, + { + "name": "comment.line.pascal", + "match": "//.*$" + } + ] + }, + "program": { + "name": "meta.program.pascal", + "begin": "(?i)\\b(program)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + } + ] + }, + "unit": { + "name": "meta.unit.pascal", + "begin": "(?i)\\b(unit)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "interface": { + "name": "meta.interface.pascal", + "begin": "(?i)\\b(interface)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(implementation)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "implementation": { + "name": "meta.implementation.pascal", + "begin": "(?i)\\b(implementation)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\b(initialization|end)\\b)", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#uses" + }, + { + "include": "#label" + }, + { + "include": "#function-declaration" + }, + { + "include": "#function-body" + }, + { + "include": "#function-mod" + }, + { + "include": "#type-declaration" + }, + { + "include": "#declaration" + } + ] + }, + "unit-main": { + "begin": "(?i)\\b(initialization)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*\\.", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(finalization)\\b" + }, + { + "include": "#statement" + } + ] + }, + "uses": { + "name": "meta.uses.pascal", + "begin": "(?i)\\b(uses)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.declaration.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "label": { + "name": "meta.label.pascal", + "begin": "(?i)\\b(label)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "include": "#comment" + }, + { + "name": "string.unquoted.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + } + ] + }, + "function-declaration": { + "name": "meta.function.pascal", + "begin": "(?i)\\b(constructor|destructor|procedure|function)\\b", + "beginCaptures": { + "1": { + "name": "storage.type.pascal" + } + }, + "end": "(?=;)", + "patterns": [ + { + "include": "#comment" + }, + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\.", + "captures": { + "1": { + "name": "entity.name.type.pascal" + } + } + }, + { + "name": "entity.name.function.pascal", + "match": "(?i)([_a-z][0-9_a-z]*)" + }, + { + "include": "#parameter-list" + }, + { + "begin": ":", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + }, + "function-body": { + "name": "meta.body.pascal", + "begin": "(?i)\\b(begin)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\s*[;|\\.]", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "function-mod": { + "begin": "(?i)\\b(alias|assembler|cdecl|external|forward|inline|interrupt|pascal|popstack|public|register|saveregisters|safecall|stdcall)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "name": "keyword.pascal", + "match": "(?i)\\b(name)\\b" + }, + { + "include": "#expression" + } + ] + }, + "asm": { + "contentName": "meta.embedded.asm", + "begin": "(?i)(asm)", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b([^;]*);", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "patterns": [ + { + "include": "#strings" + } + ] + } + }, + "patterns": [] + }, + "type-declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\btype\\b" + }, + { + "name": "meta.type.alias.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\s*(?==)", + "beginCaptures": { + "1": { + "name": "entity.name.type.pascal" + } + }, + "end": ";", + "patterns": [ + { + "begin": "=", + "end": "(?=;)", + "patterns": [ + { + "include": "#type" + } + ] + } + ] + } + ] + }, + "declaration": { + "patterns": [ + { + "include": "#comment" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(const|type|var)\\b" + }, + { + "name": "meta.declaration.pascal", + "begin": "(?i)\\b([_a-z][0-9_a-z]*)\\b", + "beginCaptures": { + "1": { + "name": "variable.other.pascal" + } + }, + "end": "(;|,|(?=\\)))", + "patterns": [ + { + "include": "#comment" + }, + { + "begin": ":", + "end": "(?=[;=)])", + "patterns": [ + { + "include": "#type" + } + ] + }, + { + "name": "meta.expression.pascal", + "match": "=([^;\\)]*)", + "captures": { + "1": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#expression" + } + ] + } + } + } + ] + } + ] + }, + "parameter-list": { + "name": "meta.parameterlist.pascal", + "begin": "\\(", + "end": "\\)", + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#declaration" + } + ] + }, + "type": { + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#class-declaration" + }, + { + "include": "#record-declaration" + }, + { + "include": "#function-declaration" + }, + { + "include": "#keywords" + }, + { + "begin": "\\[", + "end": "\\]", + "patterns": [ + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b[_a-z][0-9_a-z]*\\b" + } + ] + }, + "record-declaration": { + "begin": "(?i)\\b(record)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "begin": "(?i)\\b(case)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i)\\b(of)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)(?=\\bend\\b)", + "patterns": [ + { + "begin": "(?i):\\s*\\(", + "end": "(?i)\\)\\s*", + "patterns": [ + { + "include": "#declaration" + } + ] + }, + { + "include": "#expression" + } + ] + }, + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*:)" + }, + { + "include": "#identifier" + } + ] + }, + { + "include": "#declaration" + } + ] + }, + "class-declaration": { + "begin": "(?i)\\b(class)\\b(?:\\s*\\((.*?)\\))?", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + }, + "2": { + "name": "entity.name.type.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "name": "storage.type.method.pascal", + "match": "(?i)(private|public|protected|published)" + }, + { + "include": "#function-declaration" + }, + { + "include": "#property" + }, + { + "include": "#declaration" + } + ] + }, + "property": { + "name": "meta.property.pascal", + "begin": "(?i)\\b(property)\\b", + "beginCaptures": { + "1": { + "name": "keyword.pascal" + } + }, + "end": ";", + "patterns": [ + { + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\s*:\\s*([^;]*)", + "captures": { + "1": { + "name": "variable.other.pascal" + }, + "2": { + "patterns": [ + { + "match": "(?i)\\b(read|write|stored)\\s+([_a-z][0-9_a-z]*)\\b", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#keywords" + }, + { + "name": "entity.name.function.pascal", + "match": ".*" + } + ] + } + } + }, + { + "match": "(?i)\\b(default)\\s+(((?!\\b(?:read|write|stored|;)\\b).)*)", + "captures": { + "1": { + "name": "keyword.pascal" + }, + "2": { + "patterns": [ + { + "include": "#expression" + } + ] + } + } + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + } + } + } + ] + }, + "statement": { + "patterns": [ + { + "include": "#statement-compound" + }, + { + "include": "#expression" + } + ] + }, + "expression": { + "patterns": [ + { + "name": "constant.character.pascal", + "match": "(?i)#[0-9]+" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\$[0-9a-f]+\\b" + }, + { + "name": "constant.numeric.pascal", + "match": "(?i)\\b[0-9]+(\\.[0-9]+)?(e(\\+|\\-)?[0-9]+)?\\b" + }, + { + "include": "#strings" + }, + { + "include": "#keywords" + }, + { + "include": "#identifier" + } + ] + }, + "statement-compound": { + "name": "meta.section.pascal", + "begin": "(?i)\\b(begin|case|try)\\b", + "beginCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "end": "(?i)\\b(end)\\b", + "endCaptures": { + "1": { + "name": "keyword.control.pascal" + } + }, + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#asm" + }, + { + "include": "#statement" + } + ] + }, + "identifier": { + "patterns": [ + { + "match": "(?i)([_a-z][0-9_a-z]*)\\s*\\(", + "captures": { + "1": { + "name": "entity.name.function.pascal" + } + } + }, + { + "name": "variable.other.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b(?!\\s*\\.)" + }, + { + "name": "entity.name.class.pascal", + "match": "(?i)\\b([_a-z][0-9_a-z]*)\\b" + } + ] + }, + "keywords": { + "patterns": [ + { + "name": "entity.name.type.pascal", + "match": "(?i)\\b(string)\\b" + }, + { + "name": "keyword.control.pascal", + "match": "(?i)\\b(break|continue|do|downto|else|for|goto|if|repeat|then|until|while|with)\\b" + }, + { + "name": "constant.language.pascal", + "match": "(?i)\\b(true|false)\\b" + }, + { + "name": "keyword.pascal", + "match": "(?i)\\b(absolute|and|array|const|constructor|destructor|div|file|function|implementation|in|inherited|inline|interface|label|mod|nil|not|object|of|on|operator|or|packed|procedure|program|record|reintroduce|self|set|shl|shr|then|to|type|unit|uses|var|xor|as|class|except|exports|finalization|finally|initialization|is|library|on|property|raise|threadvar|try|dispose|exit|new)\\b" + } + ] + }, + "strings": { + "name": "string.quoted.pascal", + "begin": "'", + "end": "'(?!')", + "patterns": [ + { + "name": "constant.character.escape.pascal", + "match": "''" + } + ] + } + }, + "scopeName": "source.pascal" + } \ No newline at end of file
779
textmate: added pascal highlighting
0
.json
TextMate
mit
AvaloniaUI/AvaloniaEdit
10063492
<NME> jsgrid.min.js <BEF> /* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2017 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ !function(a,b,c){function d(a,c){var d=b(a);d.data(f,this),this._container=d,this.data=[],this.fields=[],this._editingRow=null,this._sortField=null,this._sortOrder=i,this._firstDisplayingPage=1,this._init(c),this.render()}var e="JSGrid",f=e,g="JSGridItem",h="JSGridEditRow",i="asc",j=function(a,c){return b.isFunction(a)?a.apply(c,b.makeArray(arguments).slice(2)):a},k=function(a){var c=b.Deferred();return a&&a.then?a.then(function(){c.resolve.apply(c,arguments)},function(){c.reject.apply(c,arguments)}):c.resolve(a),c.promise()},l={loadData:b.noop,insertItem:b.noop,updateItem:b.noop,deleteItem:b.noop};d.prototype={width:"auto",height:"auto",updateOnResize:!0,rowClass:b.noop,rowRenderer:null,rowClick:function(a){this.editing&&this.editItem(b(a.event.target).closest("tr"))},rowDoubleClick:b.noop,noDataContent:"Not found",noDataRowClass:"jsgrid-nodata-row",heading:!0,headerRowRenderer:null,headerRowClass:"jsgrid-header-row",headerCellClass:"jsgrid-header-cell",filtering:!1,filterRowRenderer:null,filterRowClass:"jsgrid-filter-row",inserting:!1,insertRowLocation:"bottom",insertRowRenderer:null,insertRowClass:"jsgrid-insert-row",editing:!1,editRowRenderer:null,editRowClass:"jsgrid-edit-row",confirmDeleting:!0,deleteConfirm:"Are you sure?",selecting:!0,selectedRowClass:"jsgrid-selected-row",oddRowClass:"jsgrid-row",evenRowClass:"jsgrid-alt-row",cellClass:"jsgrid-cell",sorting:!1,sortableClass:"jsgrid-header-sortable",sortAscClass:"jsgrid-header-sort jsgrid-header-sort-asc",sortDescClass:"jsgrid-header-sort jsgrid-header-sort-desc",paging:!1,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",pagerNavButtonInactiveClass:"jsgrid-pager-nav-inactive-button",pageClass:"jsgrid-pager-page",currentPageClass:"jsgrid-pager-current-page",customLoading:!1,pageLoading:!1,autoload:!1,controller:l,loadIndication:!0,loadIndicationDelay:500,loadMessage:"Please, wait...",loadShading:!0,invalidMessage:"Invalid data entered!",invalidNotify:function(c){var d=b.map(c.errors,function(a){return a.message||null});a.alert([this.invalidMessage].concat(d).join("\n"))},onInit:b.noop,onRefreshing:b.noop,onRefreshed:b.noop,onPageChanged:b.noop,onItemDeleting:b.noop,onItemDeleted:b.noop,onItemInserting:b.noop,onItemInserted:b.noop,onItemEditing:b.noop,onItemEditCancelling:b.noop,onItemUpdating:b.noop,onItemUpdated:b.noop,onItemInvalid:b.noop,onDataLoading:b.noop,onDataLoaded:b.noop,onOptionChanging:b.noop,onOptionChanged:b.noop,onError:b.noop,invalidClass:"jsgrid-invalid",containerClass:"jsgrid",tableClass:"jsgrid-table",gridHeaderClass:"jsgrid-grid-header",gridBodyClass:"jsgrid-grid-body",_init:function(a){b.extend(this,a),this._initLoadStrategy(),this._initController(),this._initFields(),this._attachWindowLoadResize(),this._attachWindowResizeCallback(),this._callEventHandler(this.onInit)},loadStrategy:function(){return this.pageLoading?new jsGrid.loadStrategies.PageLoadingStrategy(this):new jsGrid.loadStrategies.DirectLoadingStrategy(this)},_initLoadStrategy:function(){this._loadStrategy=j(this.loadStrategy,this)},_initController:function(){this._controller=b.extend({},l,j(this.controller,this))},renderTemplate:function(a,b,d){args=[];for(var e in d)args.push(d[e]);return args.unshift(a,b),a=j.apply(null,args),a===c||null===a?"":a},loadIndicator:function(a){return new jsGrid.LoadIndicator(a)},validation:function(a){return jsGrid.Validation&&new jsGrid.Validation(a)},_initFields:function(){var a=this;a.fields=b.map(a.fields,function(c){return b.isPlainObject(c)&&(c=new(c.type&&jsGrid.fields[c.type]||jsGrid.Field)(c)),c._grid=a,c})},_attachWindowLoadResize:function(){b(a).on("load",b.proxy(this._refreshSize,this))},_attachWindowResizeCallback:function(){this.updateOnResize&&b(a).on("resize",b.proxy(this._refreshSize,this))},_detachWindowResizeCallback:function(){b(a).off("resize",this._refreshSize)},option:function(a,b){var c,d;if(1===arguments.length)return this[a];c={option:a,oldValue:this[a],newValue:b},this._callEventHandler(this.onOptionChanging,c),this._handleOptionChange(c.option,c.newValue),d={option:c.option,value:c.newValue},this._callEventHandler(this.onOptionChanged,d)},fieldOption:function(a,b,c){if(a=this._normalizeField(a),2===arguments.length)return a[b];a[b]=c,this._renderGrid()},_handleOptionChange:function(a,b){switch(this[a]=b,a){case"width":case"height":this._refreshSize();break;case"rowClass":case"rowRenderer":case"rowClick":case"rowDoubleClick":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":case"pagerRenderer":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"loadStrategy":case"pageLoading":this._initLoadStrategy(),this.search();break;case"pageIndex":this.openPage(b);break;case"pageSize":this.refresh(),this.search();break;case"editRowRenderer":case"editRowClass":this.cancelEdit();break;case"updateOnResize":this._detachWindowResizeCallback(),this._attachWindowResizeCallback();break;case"invalidNotify":case"invalidMessage":break;default:this.render()}},destroy:function(){this._detachWindowResizeCallback(),this._clear(),this._container.removeData(f)},render:function(){return this._renderGrid(),this.autoload?this.loadData():b.Deferred().resolve().promise()},_renderGrid: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._validation=this._createValidation(),this.refresh()},_createLoadIndicator:function(){return j(this.loadIndicator,this,{message:this.loadMessage,shading:this.loadShading,container:this._container})},_createValidation:function(){return j(this.validation,this)},_clear:function(){this.cancelEdit(),clearTimeout(this._loadingTimer),this._pagerContainer&&this._pagerContainer.empty(),this._container.empty().css({position:"",width:"",height:""})},_createHeader:function(){var a=this._headerRow=this._createHeaderRow(),c=this._filterRow=this._createFilterRow(),d=this._insertRow=this._createInsertRow(),e=this._headerGrid=b("<table>").addClass(this.tableClass).append(a).append(c).append(d);return this._header=b("<div>").addClass(this.gridHeaderClass).addClass(this._scrollBarWidth()?"jsgrid-header-scrollbar":"").append(e)},_createBody:function(){var a=this._content=b("<tbody>"),c=this._bodyGrid=b("<table>").addClass(this.tableClass).append(a);return this._body=b("<div>").addClass(this.gridBodyClass).append(c).on("scroll",b.proxy(function(a){this._header.scrollLeft(a.target.scrollLeft)},this))},_createPagerContainer:function(){return b(this.pagerContainer||b("<div>").appendTo(this._container)).addClass(this.pagerContainerClass)},_eachField:function(a){var c=this;b.each(this.fields,function(b,d){d.visible&&a.call(c,d,b)})},_createHeaderRow:function(){if(b.isFunction(this.headerRowRenderer))return b(this.renderTemplate(this.headerRowRenderer,this));var a=b("<tr>").addClass(this.headerRowClass);return this._eachField(function(c,d){var e=this._prepareCell("<th>",c,"headercss",this.headerCellClass).append(this.renderTemplate(c.headerTemplate,c)).appendTo(a);this.sorting&&c.sorting&&e.addClass(this.sortableClass).on("click",b.proxy(function(){this.sort(d)},this))}),a},_prepareCell:function(a,c,d,e){return b(a).css("width",c.width).addClass(e||this.cellClass).addClass(d&&c[d]||c.css).addClass(c.align?"jsgrid-align-"+c.align:"")},_createFilterRow:function(){if(b.isFunction(this.filterRowRenderer))return b(this.renderTemplate(this.filterRowRenderer,this));var a=b("<tr>").addClass(this.filterRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"filtercss").append(this.renderTemplate(b.filterTemplate,b)).appendTo(a)}),a},_createInsertRow:function(){if(b.isFunction(this.insertRowRenderer))return b(this.renderTemplate(this.insertRowRenderer,this));var a=b("<tr>").addClass(this.insertRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"insertcss").append(this.renderTemplate(b.insertTemplate,b)).appendTo(a)}),a},_callEventHandler:function(a,c){return a.call(this,b.extend(c,{grid:this})),c},reset:function(){return this._resetSorting(),this._resetPager(),this._loadStrategy.reset()},_resetPager:function(){this._firstDisplayingPage=1,this._setPage(1)},_resetSorting:function(){this._sortField=null,this._sortOrder=i,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 a=this._content;if(a.empty(),!this.data.length)return a.append(this._createNoDataRow()),this;for(var b=this._loadStrategy.firstDisplayIndex(),c=this._loadStrategy.lastDisplayIndex(),d=b;d<c;d++){var e=this.data[d];a.append(this._createRow(e,d))}},_createNoDataRow:function(){var a=0;return this._eachField(function(){a++}),b("<tr>").addClass(this.noDataRowClass).append(b("<td>").addClass(this.cellClass).attr("colspan",a).append(this.renderTemplate(this.noDataContent,this)))},_createRow:function(a,c){var d;return b.isFunction(this.rowRenderer)?d=this.renderTemplate(this.rowRenderer,this,{item:a,itemIndex:c}):(d=b("<tr>"),this._renderCells(d,a)),d.addClass(this._getRowClasses(a,c)).data(g,a).on("click",b.proxy(function(b){this.rowClick({item:a,itemIndex:c,event:b})},this)).on("dblclick",b.proxy(function(b){this.rowDoubleClick({item:a,itemIndex:c,event:b})},this)),this.selecting&&this._attachRowHover(d),d},_getRowClasses:function(a,b){var c=[];return c.push((b+1)%2?this.oddRowClass:this.evenRowClass),c.push(j(this.rowClass,this,a,b)),c.join(" ")},_attachRowHover:function(a){var c=this.selectedRowClass;a.hover(function(){b(this).addClass(c)},function(){b(this).removeClass(c)})},_renderCells:function(a,b){return this._eachField(function(c){a.append(this._createCell(b,c))}),this},_createCell:function(a,c){var d,e=this._getItemFieldValue(a,c),f={value:e,item:a};return d=b.isFunction(c.cellRenderer)?this.renderTemplate(c.cellRenderer,c,f):b("<td>").append(this.renderTemplate(c.itemTemplate||e,c,f)),this._prepareCell(d,c)},_getItemFieldValue:function(a,b){for(var c=b.name.split("."),d=a[c.shift()];d&&c.length;)d=d[c.shift()];return d},_setItemFieldValue:function(a,b,c){for(var d=b.name.split("."),e=a,f=d[0];e&&d.length;)a=e,f=d.shift(),e=a[f];if(!e)for(;d.length;)a=a[f]={},f=d.shift();a[f]=c},sort:function(a,c){return b.isPlainObject(a)&&(c=a.order,a=a.field),this._clearSortingCss(),this._setSortingParams(a,c),this._setSortingCss(),this._loadStrategy.sort()},_clearSortingCss:function(){this._headerRow.find("th").removeClass(this.sortAscClass).removeClass(this.sortDescClass)},_setSortingParams:function(a,b){a=this._normalizeField(a),b=b||(this._sortField===a?this._reversedSortOrder(this._sortOrder):i),this._sortField=a,this._sortOrder=b},_normalizeField:function(a){return b.isNumeric(a)?this.fields[a]:"string"==typeof a?b.grep(this.fields,function(b){return b.name===a})[0]:a},_reversedSortOrder:function(a){return a===i?"desc":i},_setSortingCss:function(){var a=this._visibleFieldIndex(this._sortField);this._headerRow.find("th").eq(a).addClass(this._sortOrder===i?this.sortAscClass:this.sortDescClass)},_visibleFieldIndex:function(a){return b.inArray(a,b.grep(this.fields,function(a){return a.visible}))},_sortData:function(){var a=this._sortFactor(),b=this._sortField;b&&this.data.sort(function(c,d){return a*b.sortingFunc(c[b.name],d[b.name])})},_sortFactor:function(){return this._sortOrder===i?1:-1},_itemsCount:function(){return this._loadStrategy.itemsCount()},_pagesCount:function(){var a=this._itemsCount(),b=this.pageSize;return Math.floor(a/b)+(a%b?1:0)},_refreshPager:function(){var a=this._pagerContainer;a.empty(),this.paging&&a.append(this._createPager());var b=this.paging&&this._pagesCount()>1;a.toggle(b)},_createPager:function(){var a;return a=b.isFunction(this.pagerRenderer)?b(this.pagerRenderer({pageIndex:this.pageIndex,pageCount:this._pagesCount()})):b("<div>").append(this._createPagerByFormat()),a.addClass(this.pagerClass),a},_createPagerByFormat:function(){var a=this.pageIndex,c=this._pagesCount(),d=this._itemsCount(),e=this.pagerFormat.split(" ");return b.map(e,b.proxy(function(e){var f=e;return"{pages}"===e?f=this._createPages():"{first}"===e?f=this._createPagerNavButton(this.pageFirstText,1,a>1):"{prev}"===e?f=this._createPagerNavButton(this.pagePrevText,a-1,a>1):"{next}"===e?f=this._createPagerNavButton(this.pageNextText,a+1,a<c):"{last}"===e?f=this._createPagerNavButton(this.pageLastText,c,a<c):"{pageIndex}"===e?f=a:"{pageCount}"===e?f=c:"{itemCount}"===e&&(f=d),b.isArray(f)?f.concat([" "]):[f," "]},this))},_createPages:function(){var a=this._pagesCount(),b=this.pageButtonCount,c=this._firstDisplayingPage,d=[];c>1&&d.push(this._createPagerPageNavButton(this.pageNavigatorPrevText,this.showPrevPages));for(var e=0,f=c;e<b&&f<=a;e++,f++)d.push(f===this.pageIndex?this._createPagerCurrentPage():this._createPagerPage(f));return c+b-1<a&&d.push(this._createPagerPageNavButton(this.pageNavigatorNextText,this.showNextPages)),d},_createPagerNavButton:function(a,c,d){return this._createPagerButton(a,this.pagerNavButtonClass+(d?"":" "+this.pagerNavButtonInactiveClass),d?function(){this.openPage(c)}:b.noop)},_createPagerPageNavButton:function(a,b){return this._createPagerButton(a,this.pagerNavButtonClass,b)},_createPagerPage:function(a){return this._createPagerButton(a,this.pageClass,function(){this.openPage(a)})},_createPagerButton:function(a,c,d){var e=b("<a>").attr("href","javascript:void(0);").html(a).on("click",b.proxy(d,this));return b("<span>").addClass(c).append(e)},_createPagerCurrentPage:function(){return b("<span>").addClass(this.pageClass).addClass(this.currentPageClass).text(this.pageIndex)},_refreshSize:function(){this._refreshHeight(),this._refreshWidth()},_refreshWidth:function(){var a="auto"===this.width?this._getAutoWidth():this.width;this._container.width(a)},_getAutoWidth:function(){var a=this._headerGrid,b=this._header;a.width("auto");var c=a.outerWidth(),d=b.outerWidth()-b.innerWidth();return a.width(""),c+d},_scrollBarWidth:function(){var a;return function(){if(a===c){var d=b("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"),e=b("<div style='height:100px;'></div>");d.append(e).appendTo("body");var f=e.innerWidth();d.css("overflow-y","auto");var g=e.innerWidth();d.remove(),a=f-g}return a}}(),_refreshHeight:function(){var a,b=this._container,c=this._pagerContainer,d=this.height;b.height(d),"auto"!==d&&(d=b.height(),a=this._header.outerHeight(!0),c.parents(b).length&&(a+=c.outerHeight(!0)),this._body.outerHeight(d-a))},showPrevPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount;this._firstDisplayingPage=a>b?a-b:1,this._refreshPager()},showNextPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount,c=this._pagesCount();this._firstDisplayingPage=a+2*b>c?c-b+1:a+b,this._refreshPager()},openPage:function(a){a<1||a>this._pagesCount()||(this._setPage(a),this._loadStrategy.openPage(a))},_setPage:function(a){var b=this._firstDisplayingPage,c=this.pageButtonCount;this.pageIndex=a,a<b&&(this._firstDisplayingPage=a),a>b+c-1&&(this._firstDisplayingPage=a-c+1),this._callEventHandler(this.onPageChanged,{pageIndex:a})},_controllerCall:function(a,c,d,e){if(d)return b.Deferred().reject().promise();this._showLoading();var f=this._controller;if(!f||!f[a])throw Error("controller has no method '"+a+"'");return k(f[a](c)).done(b.proxy(e,this)).fail(b.proxy(this._errorHandler,this)).always(b.proxy(this._hideLoading,this))},_errorHandler:function(){this._callEventHandler(this.onError,{args:b.makeArray(arguments)})},_showLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadingTimer=setTimeout(b.proxy(function(){this._loadIndicator.show()},this),this.loadIndicationDelay))},_hideLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadIndicator.hide())},search:function(a){return this._resetSorting(),this._resetPager(),this.loadData(a)},loadData:function(a){a=a||(this.filtering?this.getFilter():{}),b.extend(a,this._loadStrategy.loadParams(),this._sortingParams());var c=this._callEventHandler(this.onDataLoading,{filter:a});return this._controllerCall("loadData",a,c.cancel,function(a){a&&(this._loadStrategy.finishLoad(a),this._callEventHandler(this.onDataLoaded,{data:a}))})},getFilter:function(){var a={};return this._eachField(function(b){b.filtering&&this._setItemFieldValue(a,b,b.filterValue())}),a},_sortingParams:function(){return this.sorting&&this._sortField?{sortField:this._sortField.name,sortOrder:this._sortOrder}:{}},getSorting:function(){var a=this._sortingParams();return{field:a.sortField,order:a.sortOrder}},clearFilter:function(){var a=this._createFilterRow();return this._filterRow.replaceWith(a),this._filterRow=a,this.search()},insertItem:function(a){var c=a||this._getValidatedInsertItem();if(!c)return b.Deferred().reject().promise();var d=this._callEventHandler(this.onItemInserting,{item:c});return this._controllerCall("insertItem",c,d.cancel,function(a){a=a||c,this._loadStrategy.finishInsert(a,this.insertRowLocation),this._callEventHandler(this.onItemInserted,{item:a})})},_getValidatedInsertItem:function(){var a=this._getInsertItem();return this._validateItem(a,this._insertRow)?a:null},_getInsertItem:function(){var a={};return this._eachField(function(b){b.inserting&&this._setItemFieldValue(a,b,b.insertValue())}),a},_validateItem:function(a,c){var d=[],e={item:a,itemIndex:this._rowIndex(c),row:c};if(this._eachField(function(f){if(f.validate&&(c!==this._insertRow||f.inserting)&&(c!==this._getEditRow()||f.editing)){var g=this._getItemFieldValue(a,f),h=this._validation.validate(b.extend({value:g,rules:f.validate},e));this._setCellValidity(c.children().eq(this._visibleFieldIndex(f)),h),h.length&&d.push.apply(d,b.map(h,function(a){return{field:f,message:a}}))}}),!d.length)return!0;var f=b.extend({errors:d},e);return this._callEventHandler(this.onItemInvalid,f),this.invalidNotify(f),!1},_setCellValidity:function(a,b){a.toggleClass(this.invalidClass,!!b.length).attr("title",b.join("\n"))},clearInsert:function(){var a=this._createInsertRow();this._insertRow.replaceWith(a),this._insertRow=a,this.refresh()},editItem:function(a){var b=this.rowByItem(a);b.length&&this._editRow(b)},rowByItem:function(a){return a.jquery||a.nodeType?b(a):this._content.find("tr").filter(function(){return b.data(this,g)===a})},_editRow:function(a){if(this.editing){var b=a.data(g);if(!this._callEventHandler(this.onItemEditing,{row:a,item:b,itemIndex:this._itemIndex(b)}).cancel){this._editingRow&&this.cancelEdit();var c=this._createEditRow(b);this._editingRow=a,a.hide(),c.insertBefore(a),a.data(h,c)}}},_createEditRow:function(a){if(b.isFunction(this.editRowRenderer))return b(this.renderTemplate(this.editRowRenderer,this,{item:a,itemIndex:this._itemIndex(a)}));var c=b("<tr>").addClass(this.editRowClass);return this._eachField(function(b){var d=this._getItemFieldValue(a,b);this._prepareCell("<td>",b,"editcss").append(this.renderTemplate(b.editTemplate||"",b,{value:d,item:a})).appendTo(c)}),c},updateItem:function(a,b){1===arguments.length&&(b=a);var c=a?this.rowByItem(a):this._editingRow;if(b=b||this._getValidatedEditedItem())return this._updateRow(c,b)},_getValidatedEditedItem:function(){var a=this._getEditedItem();return this._validateItem(a,this._getEditRow())?a:null},_updateRow:function(a,c){var d=a.data(g),e=this._itemIndex(d),f=b.extend(!0,{},d,c),h=this._callEventHandler(this.onItemUpdating,{row:a,item:f,itemIndex:e,previousItem:d});return this._controllerCall("updateItem",f,h.cancel,function(g){var h=b.extend(!0,{},d);f=g||b.extend(!0,d,c);var i=this._finishUpdate(a,f,e);this._callEventHandler(this.onItemUpdated,{row:i,item:f,itemIndex:e,previousItem:h})})},_rowIndex:function(a){return this._content.children().index(b(a))},_itemIndex:function(a){return b.inArray(a,this.data)},_finishUpdate:function(a,b,c){this.cancelEdit(),this.data[c]=b;var d=this._createRow(b,c);return a.replaceWith(d),d},_getEditedItem:function(){var a={};return this._eachField(function(b){b.editing&&this._setItemFieldValue(a,b,b.editValue())}),a},cancelEdit:function(){if(this._editingRow){var a=this._editingRow,b=a.data(g),c=this._itemIndex(b);this._callEventHandler(this.onItemEditCancelling,{row:a,item:b,itemIndex:c}),this._getEditRow().remove(),this._editingRow.show(),this._editingRow=null}},_getEditRow:function(){return this._editingRow&&this._editingRow.data(h)},deleteItem:function(b){var c=this.rowByItem(b);if(c.length&&(!this.confirmDeleting||a.confirm(j(this.deleteConfirm,this,c.data(g)))))return this._deleteRow(c)},_deleteRow:function(a){var b=a.data(g),c=this._itemIndex(b),d=this._callEventHandler(this.onItemDeleting,{row:a,item:b,itemIndex:c});return this._controllerCall("deleteItem",b,d.cancel,function(){this._loadStrategy.finishDelete(b,c),this._callEventHandler(this.onItemDeleted,{row:a,item:b,itemIndex:c})})}},b.fn.jsGrid=function(a){var e=b.makeArray(arguments),g=e.slice(1),h=this;return this.each(function(){var e,i=b(this),j=i.data(f);if(j)if("string"==typeof a){if(e=j[a].apply(j,g),e!==c&&e!==j)return h=e,!1}else j._detachWindowResizeCallback(),j._init(a),j.render();else new d(i,a)}),h};var m={},n=function(a){var c;b.isPlainObject(a)?c=d.prototype:(c=m[a].prototype,a=arguments[1]||{}),b.extend(c,a)},o={},p=function(a){var c=b.isPlainObject(a)?a:o[a];if(!c)throw Error("unknown locale "+a);q(jsGrid,c)},q=function(a,c){b.each(c,function(c,d){if(b.isPlainObject(d))return void q(a[c]||a[c[0].toUpperCase()+c.slice(1)],d);a.hasOwnProperty(c)?a[c]=d:a.prototype[c]=d})};a.jsGrid={Grid:d,fields:m,setDefaults:n,locales:o,locale:p,version:"1.5.3"}}(window,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={container:"body",message:"Loading...",shading:!0,zIndex:1e3,shaderClass:"jsgrid-load-shader",loadPanelClass:"jsgrid-load-panel",_init:function(a){b.extend(!0,this,a),this._initContainer(),this._initShader(),this._initLoadPanel()},_initContainer:function(){this._container=b(this.container)},_initShader:function(){this.shading&&(this._shader=b("<div>").addClass(this.shaderClass).hide().css({position:"absolute",top:0,right:0,bottom:0,left:0,zIndex:this.zIndex}).appendTo(this._container))},_initLoadPanel:function(){this._loadPanel=b("<div>").addClass(this.loadPanelClass).text(this.message).hide().css({position:"absolute",top:"50%",left:"50%",zIndex:this.zIndex}).appendTo(this._container)},show:function(){var a=this._loadPanel.show(),b=a.outerWidth(),c=a.outerHeight();a.css({marginTop:-c/2,marginLeft:-b/2}),this._shader.show()},hide:function(){this._loadPanel.hide(),this._shader.hide()}},a.LoadIndicator=d}(jsGrid,jQuery),function(a,b,c){function d(a){this._grid=a}function e(a){this._grid=a,this._itemsCount=0}d.prototype={firstDisplayIndex:function(){var a=this._grid;return a.option("paging")?(a.option("pageIndex")-1)*a.option("pageSize"):0},lastDisplayIndex:function(){var a=this._grid,b=a.option("data").length;return a.option("paging")?Math.min(a.option("pageIndex")*a.option("pageSize"),b):b},itemsCount:function(){return this._grid.option("data").length},openPage:function(a){this._grid.refresh()},loadParams:function(){return{}},sort:function(){return this._grid._sortData(),this._grid.refresh(),b.Deferred().resolve().promise()},reset:function(){return this._grid.refresh(),b.Deferred().resolve().promise()},finishLoad:function(a){this._grid.option("data",a)},finishInsert:function(a,b){var c=this._grid;switch(b){case"top":c.option("data").unshift(a);break;case"bottom":default:c.option("data").push(a)}c.refresh()},finishDelete:function(a,b){var c=this._grid;c.option("data").splice(b,1),c.reset()}},e.prototype={firstDisplayIndex:function(){return 0},lastDisplayIndex:function(){return this._grid.option("data").length},itemsCount:function(){return this._itemsCount},openPage:function(a){this._grid.loadData()},loadParams:function(){var a=this._grid;return{pageIndex:a.option("pageIndex"),pageSize:a.option("pageSize")}},reset:function(){return this._grid.loadData()},sort:function(){return this._grid.loadData()},finishLoad:function(a){this._itemsCount=a.itemsCount,this._grid.option("data",a.data)},finishInsert:function(a){this._grid.search()},finishDelete:function(a,b){this._grid.search()}},a.loadStrategies={DirectLoadingStrategy:d,PageLoadingStrategy:e}}(jsGrid,jQuery),function(a,b,c){var d=function(a){return void 0!==a&&null!==a},e={string:function(a,b){return d(a)||d(b)?d(a)?d(b)?(""+a).localeCompare(""+b):1:-1:0},number:function(a,b){return a-b},date:function(a,b){return a-b},numberAsString:function(a,b){return parseFloat(a)-parseFloat(b)}};a.sortStrategies=e}(jsGrid,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={_init:function(a){b.extend(!0,this,a)},validate:function(a){var c=[];return b.each(this._normalizeRules(a.rules),function(d,e){if(!e.validator(a.value,a.item,e.param)){var f=b.isFunction(e.message)?e.message(a.value,a.item):e.message;c.push(f)}}),c},_normalizeRules:function(a){return b.isArray(a)||(a=[a]),b.map(a,b.proxy(function(a){return this._normalizeRule(a)},this))},_normalizeRule:function(a){if("string"==typeof a&&(a={validator:a}),b.isFunction(a)&&(a={validator:a}),!b.isPlainObject(a))throw Error("wrong validation config specified");return a=b.extend({},a),b.isFunction(a.validator)?a:this._applyNamedValidator(a,a.validator)},_applyNamedValidator:function(a,c){delete a.validator;var d=e[c];if(!d)throw Error('unknown validator "'+c+'"');return b.isFunction(d)&&(d={validator:d}),b.extend({},d,a)}},a.Validation=d;var e={required:{message:"Field is required",validator:function(a){return a!==c&&null!==a&&""!==a}},rangeLength:{message:"Field value length is out of the defined range",validator:function(a,b,c){return a.length>=c[0]&&a.length<=c[1]}},minLength:{message:"Field value is too short",validator:function(a,b,c){return a.length>=c}},maxLength:{message:"Field value is too long",validator:function(a,b,c){return a.length<=c}},pattern:{message:"Field value is not matching the defined pattern",validator:function(a,b,c){return"string"==typeof c&&(c=new RegExp("^(?:"+c+")$")),c.test(a)}},range:{message:"Field value is out of the defined range",validator:function(a,b,c){return a>=c[0]&&a<=c[1]}},min:{message:"Field value is too small",validator:function(a,b,c){return a>=c}},max:{message:"Field value is too large",validator:function(a,b,c){return a<=c}}};a.validators=e}(jsGrid,jQuery),function(a,b,c){function d(a){b.extend(!0,this,a),this.sortingFunc=this._getSortingFunc()}d.prototype={name:"",title:null,css:"",align:"",width:100,visible:!0,filtering:!0,inserting:!0,editing:!0,sorting:!0,sorter:"string",headerTemplate:function(){return this.title===c||null===this.title?this.name:this.title},itemTemplate:function(a,b){return a},filterTemplate:function(){return""},insertTemplate:function(){return""},editTemplate:function(a,b){return this._value=a,this.itemTemplate(a,b)},filterValue:function(){return""},insertValue:function(){return""},editValue:function(){return this._value},_getSortingFunc:function(){var c=this.sorter;if(b.isFunction(c))return c;if("string"==typeof c)return a.sortStrategies[c];throw Error('wrong sorter for the field "'+this.name+'"!')}},a.Field=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({autosearch:!0,readOnly:!1,filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createTextBox();return this.autosearch&&b.on("keypress",function(b){13===b.which&&(a.search(),b.preventDefault())}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createTextBox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextBox();return b.val(a),b},filterValue:function(){return this.filterControl.val()},insertValue:function(){return this.insertControl.val()},editValue:function(){return this.editControl.val()},_createTextBox:function(){return b("<input>").attr("type","text").prop("readonly",!!this.readOnly)}}),a.fields.text=a.TextField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({sorter:"number",align:"right",readOnly:!1,filterValue:function(){return this.filterControl.val()?parseInt(this.filterControl.val()||0,10):c},insertValue:function(){return this.insertControl.val()?parseInt(this.insertControl.val()||0,10):c},editValue:function(){return this.editControl.val()?parseInt(this.editControl.val()||0,10):c},_createTextBox:function(){return b("<input>").attr("type","number").prop("readonly",!!this.readOnly)}}),a.fields.number=a.NumberField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({insertTemplate:function(){return this.inserting?this.insertControl=this._createTextArea():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextArea();return b.val(a),b},_createTextArea:function(){return b("<textarea>").prop("readonly",!!this.readOnly)}}),a.fields.textarea=a.TextAreaField=d}(jsGrid,jQuery),function(a,b,c){function d(a){if(this.items=[],this.selectedIndex=-1,this.valueField="",this.textField="",a.valueField&&a.items.length){var b=a.items[0][a.valueField];this.valueType=typeof b===f?f:g}this.sorter=this.valueType,e.call(this,a)}var e=a.NumberField,f="number",g="string";d.prototype=new e({align:"center",valueType:f,itemTemplate:function(a){var d,e=this.items,f=this.valueField,g=this.textField;d=f?b.grep(e,function(b,c){return b[f]===a})[0]||{}:e[a];var h=g?d[g]:d;return h===c||null===h?"":h},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createSelect();return this.autosearch&&b.on("change",function(b){a.search()}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createSelect():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createSelect();return a!==c&&b.val(a),b},filterValue:function(){var a=this.filterControl.val();return this.valueType===f?parseInt(a||0,10):a},insertValue:function(){var a=this.insertControl.val();return this.valueType===f?parseInt(a||0,10):a},editValue:function(){var a=this.editControl.val();return this.valueType===f?parseInt(a||0,10):a},_createSelect:function(){var a=b("<select>"),c=this.valueField,d=this.textField,e=this.selectedIndex;return b.each(this.items,function(e,f){var g=c?f[c]:e,h=d?f[d]:f;b("<option>").attr("value",g).text(h).appendTo(a)}),a.prop("disabled",!!this.readOnly),a.prop("selectedIndex",e),a}}),a.fields.select=a.SelectField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({sorter:"number",align:"center",autosearch:!0,itemTemplate:function(a){return this._createCheckbox().prop({checked:a,disabled:!0})},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,c=this.filterControl=this._createCheckbox();return c.prop({readOnly:!0,indeterminate:!0}),c.on("click",function(){var a=b(this);a.prop("readOnly")?a.prop({checked:!1,readOnly:!1}):a.prop("checked")||a.prop({readOnly:!0,indeterminate:!0})}),this.autosearch&&c.on("click",function(){a.search()}),c},insertTemplate:function(){return this.inserting?this.insertControl=this._createCheckbox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createCheckbox();return b.prop("checked",a),b},filterValue:function(){return this.filterControl.get(0).indeterminate?c:this.filterControl.is(":checked")},insertValue:function(){return this.insertControl.is(":checked")},editValue:function(){return this.editControl.is(":checked")},_createCheckbox:function(){return b("<input>").attr("type","checkbox")}}),a.fields.checkbox=a.CheckboxField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a),this._configInitialized=!1}var e=a.Field;d.prototype=new e({css:"jsgrid-control-field",align:"center",width:50,filtering:!1,inserting:!1,editing:!1,sorting:!1,buttonClass:"jsgrid-button",modeButtonClass:"jsgrid-mode-button",modeOnButtonClass:"jsgrid-mode-on-button",searchModeButtonClass:"jsgrid-search-mode-button",insertModeButtonClass:"jsgrid-insert-mode-button",editButtonClass:"jsgrid-edit-button",deleteButtonClass:"jsgrid-delete-button",searchButtonClass:"jsgrid-search-button",clearFilterButtonClass:"jsgrid-clear-filter-button",insertButtonClass:"jsgrid-insert-button",updateButtonClass:"jsgrid-update-button",cancelEditButtonClass:"jsgrid-cancel-edit-button",searchModeButtonTooltip:"Switch to searching",insertModeButtonTooltip:"Switch to inserting",editButtonTooltip:"Edit",deleteButtonTooltip:"Delete",searchButtonTooltip:"Search",clearFilterButtonTooltip:"Clear filter",insertButtonTooltip:"Insert",updateButtonTooltip:"Update",cancelEditButtonTooltip:"Cancel edit",editButton:!0,deleteButton:!0,clearFilterButton:!0,modeSwitchButton:!0,_initConfig:function(){this._hasFiltering=this._grid.filtering,this._hasInserting=this._grid.inserting,this._hasInserting&&this.modeSwitchButton&&(this._grid.inserting=!1),this._configInitialized=!0},headerTemplate:function(){this._configInitialized||this._initConfig();var a=this._hasFiltering,b=this._hasInserting;return this.modeSwitchButton&&(a||b)?a&&!b?this._createFilterSwitchButton():b&&!a?this._createInsertSwitchButton():this._createModeSwitchButton():""},itemTemplate:function(a,c){var d=b([]);return this.editButton&&(d=d.add(this._createEditButton(c))),this.deleteButton&&(d=d.add(this._createDeleteButton(c))),d},filterTemplate:function(){var a=this._createSearchButton();return this.clearFilterButton?a.add(this._createClearFilterButton()):a},insertTemplate:function(){return this._createInsertButton()},editTemplate:function(){return this._createUpdateButton().add(this._createCancelEditButton())},_createFilterSwitchButton:function(){return this._createOnOffSwitchButton("filtering",this.searchModeButtonClass,!0)},_createInsertSwitchButton:function(){return this._createOnOffSwitchButton("inserting",this.insertModeButtonClass,!1)},_createOnOffSwitchButton:function(a,c,d){var e=d,f=b.proxy(function(){g.toggleClass(this.modeOnButtonClass,e)},this),g=this._createGridButton(this.modeButtonClass+" "+c,"",function(b){e=!e,b.option(a,e),f()});return f(),g},_createModeSwitchButton:function(){var a=!1,c=b.proxy(function(){d.attr("title",a?this.searchModeButtonTooltip:this.insertModeButtonTooltip).toggleClass(this.insertModeButtonClass,!a).toggleClass(this.searchModeButtonClass,a)},this),d=this._createGridButton(this.modeButtonClass,"",function(b){a=!a,b.option("inserting",a),b.option("filtering",!a),c()});return c(),d},_createEditButton:function(a){return this._createGridButton(this.editButtonClass,this.editButtonTooltip,function(b,c){b.editItem(a),c.stopPropagation()})},_createDeleteButton:function(a){return this._createGridButton(this.deleteButtonClass,this.deleteButtonTooltip,function(b,c){b.deleteItem(a),c.stopPropagation()})},_createSearchButton:function(){return this._createGridButton(this.searchButtonClass,this.searchButtonTooltip,function(a){a.search()})},_createClearFilterButton:function(){return this._createGridButton(this.clearFilterButtonClass,this.clearFilterButtonTooltip,function(a){a.clearFilter()})},_createInsertButton:function(){return this._createGridButton(this.insertButtonClass,this.insertButtonTooltip,function(a){a.insertItem().done(function(){a.clearInsert()})})},_createUpdateButton:function(){return this._createGridButton(this.updateButtonClass,this.updateButtonTooltip,function(a,b){a.updateItem(),b.stopPropagation()})},_createCancelEditButton:function(){return this._createGridButton(this.cancelEditButtonClass,this.cancelEditButtonTooltip,function(a,b){a.cancelEdit(),b.stopPropagation()})},_createGridButton:function(a,c,d){var e=this._grid;return b("<input>").addClass(this.buttonClass).addClass(a).attr({type:"button",title:c}).on("click",function(a){d(e,a)})},editValue:function(){return""}}),a.fields.control=a.ControlField=d}(jsGrid,jQuery); <MSG> Brought dist/ back to 1.5.3 <DFF> @@ -1,7 +1,8 @@ /* * jsGrid v1.5.3 (http://js-grid.com) - * (c) 2017 Artem Tabalin + * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ -!function(a,b,c){function d(a,c){var d=b(a);d.data(f,this),this._container=d,this.data=[],this.fields=[],this._editingRow=null,this._sortField=null,this._sortOrder=i,this._firstDisplayingPage=1,this._init(c),this.render()}var e="JSGrid",f=e,g="JSGridItem",h="JSGridEditRow",i="asc",j=function(a,c){return b.isFunction(a)?a.apply(c,b.makeArray(arguments).slice(2)):a},k=function(a){var c=b.Deferred();return a&&a.then?a.then(function(){c.resolve.apply(c,arguments)},function(){c.reject.apply(c,arguments)}):c.resolve(a),c.promise()},l={loadData:b.noop,insertItem:b.noop,updateItem:b.noop,deleteItem:b.noop};d.prototype={width:"auto",height:"auto",updateOnResize:!0,rowClass:b.noop,rowRenderer:null,rowClick:function(a){this.editing&&this.editItem(b(a.event.target).closest("tr"))},rowDoubleClick:b.noop,noDataContent:"Not found",noDataRowClass:"jsgrid-nodata-row",heading:!0,headerRowRenderer:null,headerRowClass:"jsgrid-header-row",headerCellClass:"jsgrid-header-cell",filtering:!1,filterRowRenderer:null,filterRowClass:"jsgrid-filter-row",inserting:!1,insertRowLocation:"bottom",insertRowRenderer:null,insertRowClass:"jsgrid-insert-row",editing:!1,editRowRenderer:null,editRowClass:"jsgrid-edit-row",confirmDeleting:!0,deleteConfirm:"Are you sure?",selecting:!0,selectedRowClass:"jsgrid-selected-row",oddRowClass:"jsgrid-row",evenRowClass:"jsgrid-alt-row",cellClass:"jsgrid-cell",sorting:!1,sortableClass:"jsgrid-header-sortable",sortAscClass:"jsgrid-header-sort jsgrid-header-sort-asc",sortDescClass:"jsgrid-header-sort jsgrid-header-sort-desc",paging:!1,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",pagerNavButtonInactiveClass:"jsgrid-pager-nav-inactive-button",pageClass:"jsgrid-pager-page",currentPageClass:"jsgrid-pager-current-page",customLoading:!1,pageLoading:!1,autoload:!1,controller:l,loadIndication:!0,loadIndicationDelay:500,loadMessage:"Please, wait...",loadShading:!0,invalidMessage:"Invalid data entered!",invalidNotify:function(c){var d=b.map(c.errors,function(a){return a.message||null});a.alert([this.invalidMessage].concat(d).join("\n"))},onInit:b.noop,onRefreshing:b.noop,onRefreshed:b.noop,onPageChanged:b.noop,onItemDeleting:b.noop,onItemDeleted:b.noop,onItemInserting:b.noop,onItemInserted:b.noop,onItemEditing:b.noop,onItemEditCancelling:b.noop,onItemUpdating:b.noop,onItemUpdated:b.noop,onItemInvalid:b.noop,onDataLoading:b.noop,onDataLoaded:b.noop,onOptionChanging:b.noop,onOptionChanged:b.noop,onError:b.noop,invalidClass:"jsgrid-invalid",containerClass:"jsgrid",tableClass:"jsgrid-table",gridHeaderClass:"jsgrid-grid-header",gridBodyClass:"jsgrid-grid-body",_init:function(a){b.extend(this,a),this._initLoadStrategy(),this._initController(),this._initFields(),this._attachWindowLoadResize(),this._attachWindowResizeCallback(),this._callEventHandler(this.onInit)},loadStrategy:function(){return this.pageLoading?new jsGrid.loadStrategies.PageLoadingStrategy(this):new jsGrid.loadStrategies.DirectLoadingStrategy(this)},_initLoadStrategy:function(){this._loadStrategy=j(this.loadStrategy,this)},_initController:function(){this._controller=b.extend({},l,j(this.controller,this))},renderTemplate:function(a,b,d){args=[];for(var e in d)args.push(d[e]);return args.unshift(a,b),a=j.apply(null,args),a===c||null===a?"":a},loadIndicator:function(a){return new jsGrid.LoadIndicator(a)},validation:function(a){return jsGrid.Validation&&new jsGrid.Validation(a)},_initFields:function(){var a=this;a.fields=b.map(a.fields,function(c){return b.isPlainObject(c)&&(c=new(c.type&&jsGrid.fields[c.type]||jsGrid.Field)(c)),c._grid=a,c})},_attachWindowLoadResize:function(){b(a).on("load",b.proxy(this._refreshSize,this))},_attachWindowResizeCallback:function(){this.updateOnResize&&b(a).on("resize",b.proxy(this._refreshSize,this))},_detachWindowResizeCallback:function(){b(a).off("resize",this._refreshSize)},option:function(a,b){var c,d;if(1===arguments.length)return this[a];c={option:a,oldValue:this[a],newValue:b},this._callEventHandler(this.onOptionChanging,c),this._handleOptionChange(c.option,c.newValue),d={option:c.option,value:c.newValue},this._callEventHandler(this.onOptionChanged,d)},fieldOption:function(a,b,c){if(a=this._normalizeField(a),2===arguments.length)return a[b];a[b]=c,this._renderGrid()},_handleOptionChange:function(a,b){switch(this[a]=b,a){case"width":case"height":this._refreshSize();break;case"rowClass":case"rowRenderer":case"rowClick":case"rowDoubleClick":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":case"pagerRenderer":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"loadStrategy":case"pageLoading":this._initLoadStrategy(),this.search();break;case"pageIndex":this.openPage(b);break;case"pageSize":this.refresh(),this.search();break;case"editRowRenderer":case"editRowClass":this.cancelEdit();break;case"updateOnResize":this._detachWindowResizeCallback(),this._attachWindowResizeCallback();break;case"invalidNotify":case"invalidMessage":break;default:this.render()}},destroy:function(){this._detachWindowResizeCallback(),this._clear(),this._container.removeData(f)},render:function(){return this._renderGrid(),this.autoload?this.loadData():b.Deferred().resolve().promise()},_renderGrid: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._validation=this._createValidation(),this.refresh()},_createLoadIndicator:function(){return j(this.loadIndicator,this,{message:this.loadMessage,shading:this.loadShading,container:this._container})},_createValidation:function(){return j(this.validation,this)},_clear:function(){this.cancelEdit(),clearTimeout(this._loadingTimer),this._pagerContainer&&this._pagerContainer.empty(),this._container.empty().css({position:"",width:"",height:""})},_createHeader:function(){var a=this._headerRow=this._createHeaderRow(),c=this._filterRow=this._createFilterRow(),d=this._insertRow=this._createInsertRow(),e=this._headerGrid=b("<table>").addClass(this.tableClass).append(a).append(c).append(d);return this._header=b("<div>").addClass(this.gridHeaderClass).addClass(this._scrollBarWidth()?"jsgrid-header-scrollbar":"").append(e)},_createBody:function(){var a=this._content=b("<tbody>"),c=this._bodyGrid=b("<table>").addClass(this.tableClass).append(a);return this._body=b("<div>").addClass(this.gridBodyClass).append(c).on("scroll",b.proxy(function(a){this._header.scrollLeft(a.target.scrollLeft)},this))},_createPagerContainer:function(){return b(this.pagerContainer||b("<div>").appendTo(this._container)).addClass(this.pagerContainerClass)},_eachField:function(a){var c=this;b.each(this.fields,function(b,d){d.visible&&a.call(c,d,b)})},_createHeaderRow:function(){if(b.isFunction(this.headerRowRenderer))return b(this.renderTemplate(this.headerRowRenderer,this));var a=b("<tr>").addClass(this.headerRowClass);return this._eachField(function(c,d){var e=this._prepareCell("<th>",c,"headercss",this.headerCellClass).append(this.renderTemplate(c.headerTemplate,c)).appendTo(a);this.sorting&&c.sorting&&e.addClass(this.sortableClass).on("click",b.proxy(function(){this.sort(d)},this))}),a},_prepareCell:function(a,c,d,e){return b(a).css("width",c.width).addClass(e||this.cellClass).addClass(d&&c[d]||c.css).addClass(c.align?"jsgrid-align-"+c.align:"")},_createFilterRow:function(){if(b.isFunction(this.filterRowRenderer))return b(this.renderTemplate(this.filterRowRenderer,this));var a=b("<tr>").addClass(this.filterRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"filtercss").append(this.renderTemplate(b.filterTemplate,b)).appendTo(a)}),a},_createInsertRow:function(){if(b.isFunction(this.insertRowRenderer))return b(this.renderTemplate(this.insertRowRenderer,this));var a=b("<tr>").addClass(this.insertRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"insertcss").append(this.renderTemplate(b.insertTemplate,b)).appendTo(a)}),a},_callEventHandler:function(a,c){return a.call(this,b.extend(c,{grid:this})),c},reset:function(){return this._resetSorting(),this._resetPager(),this._loadStrategy.reset()},_resetPager:function(){this._firstDisplayingPage=1,this._setPage(1)},_resetSorting:function(){this._sortField=null,this._sortOrder=i,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 a=this._content;if(a.empty(),!this.data.length)return a.append(this._createNoDataRow()),this;for(var b=this._loadStrategy.firstDisplayIndex(),c=this._loadStrategy.lastDisplayIndex(),d=b;d<c;d++){var e=this.data[d];a.append(this._createRow(e,d))}},_createNoDataRow:function(){var a=0;return this._eachField(function(){a++}),b("<tr>").addClass(this.noDataRowClass).append(b("<td>").addClass(this.cellClass).attr("colspan",a).append(this.renderTemplate(this.noDataContent,this)))},_createRow:function(a,c){var d;return b.isFunction(this.rowRenderer)?d=this.renderTemplate(this.rowRenderer,this,{item:a,itemIndex:c}):(d=b("<tr>"),this._renderCells(d,a)),d.addClass(this._getRowClasses(a,c)).data(g,a).on("click",b.proxy(function(b){this.rowClick({item:a,itemIndex:c,event:b})},this)).on("dblclick",b.proxy(function(b){this.rowDoubleClick({item:a,itemIndex:c,event:b})},this)),this.selecting&&this._attachRowHover(d),d},_getRowClasses:function(a,b){var c=[];return c.push((b+1)%2?this.oddRowClass:this.evenRowClass),c.push(j(this.rowClass,this,a,b)),c.join(" ")},_attachRowHover:function(a){var c=this.selectedRowClass;a.hover(function(){b(this).addClass(c)},function(){b(this).removeClass(c)})},_renderCells:function(a,b){return this._eachField(function(c){a.append(this._createCell(b,c))}),this},_createCell:function(a,c){var d,e=this._getItemFieldValue(a,c),f={value:e,item:a};return d=b.isFunction(c.cellRenderer)?this.renderTemplate(c.cellRenderer,c,f):b("<td>").append(this.renderTemplate(c.itemTemplate||e,c,f)),this._prepareCell(d,c)},_getItemFieldValue:function(a,b){for(var c=b.name.split("."),d=a[c.shift()];d&&c.length;)d=d[c.shift()];return d},_setItemFieldValue:function(a,b,c){for(var d=b.name.split("."),e=a,f=d[0];e&&d.length;)a=e,f=d.shift(),e=a[f];if(!e)for(;d.length;)a=a[f]={},f=d.shift();a[f]=c},sort:function(a,c){return b.isPlainObject(a)&&(c=a.order,a=a.field),this._clearSortingCss(),this._setSortingParams(a,c),this._setSortingCss(),this._loadStrategy.sort()},_clearSortingCss:function(){this._headerRow.find("th").removeClass(this.sortAscClass).removeClass(this.sortDescClass)},_setSortingParams:function(a,b){a=this._normalizeField(a),b=b||(this._sortField===a?this._reversedSortOrder(this._sortOrder):i),this._sortField=a,this._sortOrder=b},_normalizeField:function(a){return b.isNumeric(a)?this.fields[a]:"string"==typeof a?b.grep(this.fields,function(b){return b.name===a})[0]:a},_reversedSortOrder:function(a){return a===i?"desc":i},_setSortingCss:function(){var a=this._visibleFieldIndex(this._sortField);this._headerRow.find("th").eq(a).addClass(this._sortOrder===i?this.sortAscClass:this.sortDescClass)},_visibleFieldIndex:function(a){return b.inArray(a,b.grep(this.fields,function(a){return a.visible}))},_sortData:function(){var a=this._sortFactor(),b=this._sortField;b&&this.data.sort(function(c,d){return a*b.sortingFunc(c[b.name],d[b.name])})},_sortFactor:function(){return this._sortOrder===i?1:-1},_itemsCount:function(){return this._loadStrategy.itemsCount()},_pagesCount:function(){var a=this._itemsCount(),b=this.pageSize;return Math.floor(a/b)+(a%b?1:0)},_refreshPager:function(){var a=this._pagerContainer;a.empty(),this.paging&&a.append(this._createPager());var b=this.paging&&this._pagesCount()>1;a.toggle(b)},_createPager:function(){var a;return a=b.isFunction(this.pagerRenderer)?b(this.pagerRenderer({pageIndex:this.pageIndex,pageCount:this._pagesCount()})):b("<div>").append(this._createPagerByFormat()),a.addClass(this.pagerClass),a},_createPagerByFormat:function(){var a=this.pageIndex,c=this._pagesCount(),d=this._itemsCount(),e=this.pagerFormat.split(" ");return b.map(e,b.proxy(function(e){var f=e;return"{pages}"===e?f=this._createPages():"{first}"===e?f=this._createPagerNavButton(this.pageFirstText,1,a>1):"{prev}"===e?f=this._createPagerNavButton(this.pagePrevText,a-1,a>1):"{next}"===e?f=this._createPagerNavButton(this.pageNextText,a+1,a<c):"{last}"===e?f=this._createPagerNavButton(this.pageLastText,c,a<c):"{pageIndex}"===e?f=a:"{pageCount}"===e?f=c:"{itemCount}"===e&&(f=d),b.isArray(f)?f.concat([" "]):[f," "]},this))},_createPages:function(){var a=this._pagesCount(),b=this.pageButtonCount,c=this._firstDisplayingPage,d=[];c>1&&d.push(this._createPagerPageNavButton(this.pageNavigatorPrevText,this.showPrevPages));for(var e=0,f=c;e<b&&f<=a;e++,f++)d.push(f===this.pageIndex?this._createPagerCurrentPage():this._createPagerPage(f));return c+b-1<a&&d.push(this._createPagerPageNavButton(this.pageNavigatorNextText,this.showNextPages)),d},_createPagerNavButton:function(a,c,d){return this._createPagerButton(a,this.pagerNavButtonClass+(d?"":" "+this.pagerNavButtonInactiveClass),d?function(){this.openPage(c)}:b.noop)},_createPagerPageNavButton:function(a,b){return this._createPagerButton(a,this.pagerNavButtonClass,b)},_createPagerPage:function(a){return this._createPagerButton(a,this.pageClass,function(){this.openPage(a)})},_createPagerButton:function(a,c,d){var e=b("<a>").attr("href","javascript:void(0);").html(a).on("click",b.proxy(d,this));return b("<span>").addClass(c).append(e)},_createPagerCurrentPage:function(){return b("<span>").addClass(this.pageClass).addClass(this.currentPageClass).text(this.pageIndex)},_refreshSize:function(){this._refreshHeight(),this._refreshWidth()},_refreshWidth:function(){var a="auto"===this.width?this._getAutoWidth():this.width;this._container.width(a)},_getAutoWidth:function(){var a=this._headerGrid,b=this._header;a.width("auto");var c=a.outerWidth(),d=b.outerWidth()-b.innerWidth();return a.width(""),c+d},_scrollBarWidth:function(){var a;return function(){if(a===c){var d=b("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"),e=b("<div style='height:100px;'></div>");d.append(e).appendTo("body");var f=e.innerWidth();d.css("overflow-y","auto");var g=e.innerWidth();d.remove(),a=f-g}return a}}(),_refreshHeight:function(){var a,b=this._container,c=this._pagerContainer,d=this.height;b.height(d),"auto"!==d&&(d=b.height(),a=this._header.outerHeight(!0),c.parents(b).length&&(a+=c.outerHeight(!0)),this._body.outerHeight(d-a))},showPrevPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount;this._firstDisplayingPage=a>b?a-b:1,this._refreshPager()},showNextPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount,c=this._pagesCount();this._firstDisplayingPage=a+2*b>c?c-b+1:a+b,this._refreshPager()},openPage:function(a){a<1||a>this._pagesCount()||(this._setPage(a),this._loadStrategy.openPage(a))},_setPage:function(a){var b=this._firstDisplayingPage,c=this.pageButtonCount;this.pageIndex=a,a<b&&(this._firstDisplayingPage=a),a>b+c-1&&(this._firstDisplayingPage=a-c+1),this._callEventHandler(this.onPageChanged,{pageIndex:a})},_controllerCall:function(a,c,d,e){if(d)return b.Deferred().reject().promise();this._showLoading();var f=this._controller;if(!f||!f[a])throw Error("controller has no method '"+a+"'");return k(f[a](c)).done(b.proxy(e,this)).fail(b.proxy(this._errorHandler,this)).always(b.proxy(this._hideLoading,this))},_errorHandler:function(){this._callEventHandler(this.onError,{args:b.makeArray(arguments)})},_showLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadingTimer=setTimeout(b.proxy(function(){this._loadIndicator.show()},this),this.loadIndicationDelay))},_hideLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadIndicator.hide())},search:function(a){return this._resetSorting(),this._resetPager(),this.loadData(a)},loadData:function(a){a=a||(this.filtering?this.getFilter():{}),b.extend(a,this._loadStrategy.loadParams(),this._sortingParams());var c=this._callEventHandler(this.onDataLoading,{filter:a});return this._controllerCall("loadData",a,c.cancel,function(a){a&&(this._loadStrategy.finishLoad(a),this._callEventHandler(this.onDataLoaded,{data:a}))})},getFilter:function(){var a={};return this._eachField(function(b){b.filtering&&this._setItemFieldValue(a,b,b.filterValue())}),a},_sortingParams:function(){return this.sorting&&this._sortField?{sortField:this._sortField.name,sortOrder:this._sortOrder}:{}},getSorting:function(){var a=this._sortingParams();return{field:a.sortField,order:a.sortOrder}},clearFilter:function(){var a=this._createFilterRow();return this._filterRow.replaceWith(a),this._filterRow=a,this.search()},insertItem:function(a){var c=a||this._getValidatedInsertItem();if(!c)return b.Deferred().reject().promise();var d=this._callEventHandler(this.onItemInserting,{item:c});return this._controllerCall("insertItem",c,d.cancel,function(a){a=a||c,this._loadStrategy.finishInsert(a,this.insertRowLocation),this._callEventHandler(this.onItemInserted,{item:a})})},_getValidatedInsertItem:function(){var a=this._getInsertItem();return this._validateItem(a,this._insertRow)?a:null},_getInsertItem:function(){var a={};return this._eachField(function(b){b.inserting&&this._setItemFieldValue(a,b,b.insertValue())}),a},_validateItem:function(a,c){var d=[],e={item:a,itemIndex:this._rowIndex(c),row:c};if(this._eachField(function(f){if(f.validate&&(c!==this._insertRow||f.inserting)&&(c!==this._getEditRow()||f.editing)){var g=this._getItemFieldValue(a,f),h=this._validation.validate(b.extend({value:g,rules:f.validate},e));this._setCellValidity(c.children().eq(this._visibleFieldIndex(f)),h),h.length&&d.push.apply(d,b.map(h,function(a){return{field:f,message:a}}))}}),!d.length)return!0;var f=b.extend({errors:d},e);return this._callEventHandler(this.onItemInvalid,f),this.invalidNotify(f),!1},_setCellValidity:function(a,b){a.toggleClass(this.invalidClass,!!b.length).attr("title",b.join("\n"))},clearInsert:function(){var a=this._createInsertRow();this._insertRow.replaceWith(a),this._insertRow=a,this.refresh()},editItem:function(a){var b=this.rowByItem(a);b.length&&this._editRow(b)},rowByItem:function(a){return a.jquery||a.nodeType?b(a):this._content.find("tr").filter(function(){return b.data(this,g)===a})},_editRow:function(a){if(this.editing){var b=a.data(g);if(!this._callEventHandler(this.onItemEditing,{row:a,item:b,itemIndex:this._itemIndex(b)}).cancel){this._editingRow&&this.cancelEdit();var c=this._createEditRow(b);this._editingRow=a,a.hide(),c.insertBefore(a),a.data(h,c)}}},_createEditRow:function(a){if(b.isFunction(this.editRowRenderer))return b(this.renderTemplate(this.editRowRenderer,this,{item:a,itemIndex:this._itemIndex(a)}));var c=b("<tr>").addClass(this.editRowClass);return this._eachField(function(b){var d=this._getItemFieldValue(a,b);this._prepareCell("<td>",b,"editcss").append(this.renderTemplate(b.editTemplate||"",b,{value:d,item:a})).appendTo(c)}),c},updateItem:function(a,b){1===arguments.length&&(b=a);var c=a?this.rowByItem(a):this._editingRow;if(b=b||this._getValidatedEditedItem())return this._updateRow(c,b)},_getValidatedEditedItem:function(){var a=this._getEditedItem();return this._validateItem(a,this._getEditRow())?a:null},_updateRow:function(a,c){var d=a.data(g),e=this._itemIndex(d),f=b.extend(!0,{},d,c),h=this._callEventHandler(this.onItemUpdating,{row:a,item:f,itemIndex:e,previousItem:d});return this._controllerCall("updateItem",f,h.cancel,function(g){var h=b.extend(!0,{},d);f=g||b.extend(!0,d,c);var i=this._finishUpdate(a,f,e);this._callEventHandler(this.onItemUpdated,{row:i,item:f,itemIndex:e,previousItem:h})})},_rowIndex:function(a){return this._content.children().index(b(a))},_itemIndex:function(a){return b.inArray(a,this.data)},_finishUpdate:function(a,b,c){this.cancelEdit(),this.data[c]=b;var d=this._createRow(b,c);return a.replaceWith(d),d},_getEditedItem:function(){var a={};return this._eachField(function(b){b.editing&&this._setItemFieldValue(a,b,b.editValue())}),a},cancelEdit:function(){if(this._editingRow){var a=this._editingRow,b=a.data(g),c=this._itemIndex(b);this._callEventHandler(this.onItemEditCancelling,{row:a,item:b,itemIndex:c}),this._getEditRow().remove(),this._editingRow.show(),this._editingRow=null}},_getEditRow:function(){return this._editingRow&&this._editingRow.data(h)},deleteItem:function(b){var c=this.rowByItem(b);if(c.length&&(!this.confirmDeleting||a.confirm(j(this.deleteConfirm,this,c.data(g)))))return this._deleteRow(c)},_deleteRow:function(a){var b=a.data(g),c=this._itemIndex(b),d=this._callEventHandler(this.onItemDeleting,{row:a,item:b,itemIndex:c});return this._controllerCall("deleteItem",b,d.cancel,function(){this._loadStrategy.finishDelete(b,c),this._callEventHandler(this.onItemDeleted,{row:a,item:b,itemIndex:c})})}},b.fn.jsGrid=function(a){var e=b.makeArray(arguments),g=e.slice(1),h=this;return this.each(function(){var e,i=b(this),j=i.data(f);if(j)if("string"==typeof a){if(e=j[a].apply(j,g),e!==c&&e!==j)return h=e,!1}else j._detachWindowResizeCallback(),j._init(a),j.render();else new d(i,a)}),h};var m={},n=function(a){var c;b.isPlainObject(a)?c=d.prototype:(c=m[a].prototype,a=arguments[1]||{}),b.extend(c,a)},o={},p=function(a){var c=b.isPlainObject(a)?a:o[a];if(!c)throw Error("unknown locale "+a);q(jsGrid,c)},q=function(a,c){b.each(c,function(c,d){if(b.isPlainObject(d))return void q(a[c]||a[c[0].toUpperCase()+c.slice(1)],d);a.hasOwnProperty(c)?a[c]=d:a.prototype[c]=d})};a.jsGrid={Grid:d,fields:m,setDefaults:n,locales:o,locale:p,version:"1.5.3"}}(window,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={container:"body",message:"Loading...",shading:!0,zIndex:1e3,shaderClass:"jsgrid-load-shader",loadPanelClass:"jsgrid-load-panel",_init:function(a){b.extend(!0,this,a),this._initContainer(),this._initShader(),this._initLoadPanel()},_initContainer:function(){this._container=b(this.container)},_initShader:function(){this.shading&&(this._shader=b("<div>").addClass(this.shaderClass).hide().css({position:"absolute",top:0,right:0,bottom:0,left:0,zIndex:this.zIndex}).appendTo(this._container))},_initLoadPanel:function(){this._loadPanel=b("<div>").addClass(this.loadPanelClass).text(this.message).hide().css({position:"absolute",top:"50%",left:"50%",zIndex:this.zIndex}).appendTo(this._container)},show:function(){var a=this._loadPanel.show(),b=a.outerWidth(),c=a.outerHeight();a.css({marginTop:-c/2,marginLeft:-b/2}),this._shader.show()},hide:function(){this._loadPanel.hide(),this._shader.hide()}},a.LoadIndicator=d}(jsGrid,jQuery),function(a,b,c){function d(a){this._grid=a}function e(a){this._grid=a,this._itemsCount=0}d.prototype={firstDisplayIndex:function(){var a=this._grid;return a.option("paging")?(a.option("pageIndex")-1)*a.option("pageSize"):0},lastDisplayIndex:function(){var a=this._grid,b=a.option("data").length;return a.option("paging")?Math.min(a.option("pageIndex")*a.option("pageSize"),b):b},itemsCount:function(){return this._grid.option("data").length},openPage:function(a){this._grid.refresh()},loadParams:function(){return{}},sort:function(){return this._grid._sortData(),this._grid.refresh(),b.Deferred().resolve().promise()},reset:function(){return this._grid.refresh(),b.Deferred().resolve().promise()},finishLoad:function(a){this._grid.option("data",a)},finishInsert:function(a,b){var c=this._grid;switch(b){case"top":c.option("data").unshift(a);break;case"bottom":default:c.option("data").push(a)}c.refresh()},finishDelete:function(a,b){var c=this._grid;c.option("data").splice(b,1),c.reset()}},e.prototype={firstDisplayIndex:function(){return 0},lastDisplayIndex:function(){return this._grid.option("data").length},itemsCount:function(){return this._itemsCount},openPage:function(a){this._grid.loadData()},loadParams:function(){var a=this._grid;return{pageIndex:a.option("pageIndex"),pageSize:a.option("pageSize")}},reset:function(){return this._grid.loadData()},sort:function(){return this._grid.loadData()},finishLoad:function(a){this._itemsCount=a.itemsCount,this._grid.option("data",a.data)},finishInsert:function(a){this._grid.search()},finishDelete:function(a,b){this._grid.search()}},a.loadStrategies={DirectLoadingStrategy:d,PageLoadingStrategy:e}}(jsGrid,jQuery),function(a,b,c){var d=function(a){return void 0!==a&&null!==a},e={string:function(a,b){return d(a)||d(b)?d(a)?d(b)?(""+a).localeCompare(""+b):1:-1:0},number:function(a,b){return a-b},date:function(a,b){return a-b},numberAsString:function(a,b){return parseFloat(a)-parseFloat(b)}};a.sortStrategies=e}(jsGrid,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={_init:function(a){b.extend(!0,this,a)},validate:function(a){var c=[];return b.each(this._normalizeRules(a.rules),function(d,e){if(!e.validator(a.value,a.item,e.param)){var f=b.isFunction(e.message)?e.message(a.value,a.item):e.message;c.push(f)}}),c},_normalizeRules:function(a){return b.isArray(a)||(a=[a]),b.map(a,b.proxy(function(a){return this._normalizeRule(a)},this))},_normalizeRule:function(a){if("string"==typeof a&&(a={validator:a}),b.isFunction(a)&&(a={validator:a}),!b.isPlainObject(a))throw Error("wrong validation config specified");return a=b.extend({},a),b.isFunction(a.validator)?a:this._applyNamedValidator(a,a.validator)},_applyNamedValidator:function(a,c){delete a.validator;var d=e[c];if(!d)throw Error('unknown validator "'+c+'"');return b.isFunction(d)&&(d={validator:d}),b.extend({},d,a)}},a.Validation=d;var e={required:{message:"Field is required",validator:function(a){return a!==c&&null!==a&&""!==a}},rangeLength:{message:"Field value length is out of the defined range",validator:function(a,b,c){return a.length>=c[0]&&a.length<=c[1]}},minLength:{message:"Field value is too short",validator:function(a,b,c){return a.length>=c}},maxLength:{message:"Field value is too long",validator:function(a,b,c){return a.length<=c}},pattern:{message:"Field value is not matching the defined pattern",validator:function(a,b,c){return"string"==typeof c&&(c=new RegExp("^(?:"+c+")$")),c.test(a)}},range:{message:"Field value is out of the defined range",validator:function(a,b,c){return a>=c[0]&&a<=c[1]}},min:{message:"Field value is too small",validator:function(a,b,c){return a>=c}},max:{message:"Field value is too large",validator:function(a,b,c){return a<=c}}};a.validators=e}(jsGrid,jQuery),function(a,b,c){function d(a){b.extend(!0,this,a),this.sortingFunc=this._getSortingFunc()}d.prototype={name:"",title:null,css:"",align:"",width:100,visible:!0,filtering:!0,inserting:!0,editing:!0,sorting:!0,sorter:"string",headerTemplate:function(){return this.title===c||null===this.title?this.name:this.title},itemTemplate:function(a,b){return a},filterTemplate:function(){return""},insertTemplate:function(){return""},editTemplate:function(a,b){return this._value=a,this.itemTemplate(a,b)},filterValue:function(){return""},insertValue:function(){return""},editValue:function(){return this._value},_getSortingFunc:function(){var c=this.sorter;if(b.isFunction(c))return c;if("string"==typeof c)return a.sortStrategies[c];throw Error('wrong sorter for the field "'+this.name+'"!')}},a.Field=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({autosearch:!0,readOnly:!1,filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createTextBox();return this.autosearch&&b.on("keypress",function(b){13===b.which&&(a.search(),b.preventDefault())}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createTextBox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextBox();return b.val(a),b},filterValue:function(){return this.filterControl.val()},insertValue:function(){return this.insertControl.val()},editValue:function(){return this.editControl.val()},_createTextBox:function(){return b("<input>").attr("type","text").prop("readonly",!!this.readOnly)}}),a.fields.text=a.TextField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({sorter:"number",align:"right",readOnly:!1,filterValue:function(){return this.filterControl.val()?parseInt(this.filterControl.val()||0,10):c},insertValue:function(){return this.insertControl.val()?parseInt(this.insertControl.val()||0,10):c},editValue:function(){return this.editControl.val()?parseInt(this.editControl.val()||0,10):c},_createTextBox:function(){return b("<input>").attr("type","number").prop("readonly",!!this.readOnly)}}),a.fields.number=a.NumberField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({insertTemplate:function(){return this.inserting?this.insertControl=this._createTextArea():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextArea();return b.val(a),b},_createTextArea:function(){return b("<textarea>").prop("readonly",!!this.readOnly)}}),a.fields.textarea=a.TextAreaField=d}(jsGrid,jQuery),function(a,b,c){function d(a){if(this.items=[],this.selectedIndex=-1,this.valueField="",this.textField="",a.valueField&&a.items.length){var b=a.items[0][a.valueField];this.valueType=typeof b===f?f:g}this.sorter=this.valueType,e.call(this,a)}var e=a.NumberField,f="number",g="string";d.prototype=new e({align:"center",valueType:f,itemTemplate:function(a){var d,e=this.items,f=this.valueField,g=this.textField;d=f?b.grep(e,function(b,c){return b[f]===a})[0]||{}:e[a];var h=g?d[g]:d;return h===c||null===h?"":h},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createSelect();return this.autosearch&&b.on("change",function(b){a.search()}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createSelect():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createSelect();return a!==c&&b.val(a),b},filterValue:function(){var a=this.filterControl.val();return this.valueType===f?parseInt(a||0,10):a},insertValue:function(){var a=this.insertControl.val();return this.valueType===f?parseInt(a||0,10):a},editValue:function(){var a=this.editControl.val();return this.valueType===f?parseInt(a||0,10):a},_createSelect:function(){var a=b("<select>"),c=this.valueField,d=this.textField,e=this.selectedIndex;return b.each(this.items,function(e,f){var g=c?f[c]:e,h=d?f[d]:f;b("<option>").attr("value",g).text(h).appendTo(a)}),a.prop("disabled",!!this.readOnly),a.prop("selectedIndex",e),a}}),a.fields.select=a.SelectField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({sorter:"number",align:"center",autosearch:!0,itemTemplate:function(a){return this._createCheckbox().prop({checked:a,disabled:!0})},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,c=this.filterControl=this._createCheckbox();return c.prop({readOnly:!0,indeterminate:!0}),c.on("click",function(){var a=b(this);a.prop("readOnly")?a.prop({checked:!1,readOnly:!1}):a.prop("checked")||a.prop({readOnly:!0,indeterminate:!0})}),this.autosearch&&c.on("click",function(){a.search()}),c},insertTemplate:function(){return this.inserting?this.insertControl=this._createCheckbox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createCheckbox();return b.prop("checked",a),b},filterValue:function(){return this.filterControl.get(0).indeterminate?c:this.filterControl.is(":checked")},insertValue:function(){return this.insertControl.is(":checked")},editValue:function(){return this.editControl.is(":checked")},_createCheckbox:function(){return b("<input>").attr("type","checkbox")}}),a.fields.checkbox=a.CheckboxField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a),this._configInitialized=!1}var e=a.Field;d.prototype=new e({css:"jsgrid-control-field",align:"center",width:50,filtering:!1,inserting:!1,editing:!1,sorting:!1,buttonClass:"jsgrid-button",modeButtonClass:"jsgrid-mode-button",modeOnButtonClass:"jsgrid-mode-on-button",searchModeButtonClass:"jsgrid-search-mode-button",insertModeButtonClass:"jsgrid-insert-mode-button",editButtonClass:"jsgrid-edit-button",deleteButtonClass:"jsgrid-delete-button",searchButtonClass:"jsgrid-search-button",clearFilterButtonClass:"jsgrid-clear-filter-button",insertButtonClass:"jsgrid-insert-button",updateButtonClass:"jsgrid-update-button",cancelEditButtonClass:"jsgrid-cancel-edit-button",searchModeButtonTooltip:"Switch to searching",insertModeButtonTooltip:"Switch to inserting",editButtonTooltip:"Edit",deleteButtonTooltip:"Delete",searchButtonTooltip:"Search",clearFilterButtonTooltip:"Clear filter",insertButtonTooltip:"Insert",updateButtonTooltip:"Update",cancelEditButtonTooltip:"Cancel edit",editButton:!0,deleteButton:!0,clearFilterButton:!0,modeSwitchButton:!0,_initConfig:function(){this._hasFiltering=this._grid.filtering,this._hasInserting=this._grid.inserting,this._hasInserting&&this.modeSwitchButton&&(this._grid.inserting=!1),this._configInitialized=!0},headerTemplate:function(){this._configInitialized||this._initConfig();var a=this._hasFiltering,b=this._hasInserting;return this.modeSwitchButton&&(a||b)?a&&!b?this._createFilterSwitchButton():b&&!a?this._createInsertSwitchButton():this._createModeSwitchButton():""},itemTemplate:function(a,c){var d=b([]);return this.editButton&&(d=d.add(this._createEditButton(c))),this.deleteButton&&(d=d.add(this._createDeleteButton(c))),d},filterTemplate:function(){var a=this._createSearchButton();return this.clearFilterButton?a.add(this._createClearFilterButton()):a},insertTemplate:function(){return this._createInsertButton()},editTemplate:function(){return this._createUpdateButton().add(this._createCancelEditButton())},_createFilterSwitchButton:function(){return this._createOnOffSwitchButton("filtering",this.searchModeButtonClass,!0)},_createInsertSwitchButton:function(){return this._createOnOffSwitchButton("inserting",this.insertModeButtonClass,!1)},_createOnOffSwitchButton:function(a,c,d){var e=d,f=b.proxy(function(){g.toggleClass(this.modeOnButtonClass,e)},this),g=this._createGridButton(this.modeButtonClass+" "+c,"",function(b){e=!e,b.option(a,e),f()});return f(),g},_createModeSwitchButton:function(){var a=!1,c=b.proxy(function(){d.attr("title",a?this.searchModeButtonTooltip:this.insertModeButtonTooltip).toggleClass(this.insertModeButtonClass,!a).toggleClass(this.searchModeButtonClass,a)},this),d=this._createGridButton(this.modeButtonClass,"",function(b){a=!a,b.option("inserting",a),b.option("filtering",!a),c()});return c(),d},_createEditButton:function(a){return this._createGridButton(this.editButtonClass,this.editButtonTooltip,function(b,c){b.editItem(a),c.stopPropagation()})},_createDeleteButton:function(a){return this._createGridButton(this.deleteButtonClass,this.deleteButtonTooltip,function(b,c){b.deleteItem(a),c.stopPropagation()})},_createSearchButton:function(){return this._createGridButton(this.searchButtonClass,this.searchButtonTooltip,function(a){a.search()})},_createClearFilterButton:function(){return this._createGridButton(this.clearFilterButtonClass,this.clearFilterButtonTooltip,function(a){a.clearFilter()})},_createInsertButton:function(){return this._createGridButton(this.insertButtonClass,this.insertButtonTooltip,function(a){a.insertItem().done(function(){a.clearInsert()})})},_createUpdateButton:function(){return this._createGridButton(this.updateButtonClass,this.updateButtonTooltip,function(a,b){a.updateItem(),b.stopPropagation()})},_createCancelEditButton:function(){return this._createGridButton(this.cancelEditButtonClass,this.cancelEditButtonTooltip,function(a,b){a.cancelEdit(),b.stopPropagation()})},_createGridButton:function(a,c,d){var e=this._grid;return b("<input>").addClass(this.buttonClass).addClass(a).attr({type:"button",title:c}).on("click",function(a){d(e,a)})},editValue:function(){return""}}),a.fields.control=a.ControlField=d}(jsGrid,jQuery); \ No newline at end of file +!function(a,b,c){function d(a,c){var d=b(a);d.data(f,this),this._container=d,this.data=[],this.fields=[],this._editingRow=null,this._sortField=null,this._sortOrder=i,this._firstDisplayingPage=1,this._init(c),this.render()}var e="JSGrid",f=e,g="JSGridItem",h="JSGridEditRow",i="asc",j="desc",k="{first}",l="{pages}",m="{prev}",n="{next}",o="{last}",p="{pageIndex}",q="{pageCount}",r="{itemCount}",s="javascript:void(0);",t=function(a,c){return b.isFunction(a)?a.apply(c,b.makeArray(arguments).slice(2)):a},u=function(a){var c=b.Deferred();return a&&a.then?a.then(function(){c.resolve.apply(c,arguments)},function(){c.reject.apply(c,arguments)}):c.resolve(a),c.promise()},v={loadData:b.noop,insertItem:b.noop,updateItem:b.noop,deleteItem:b.noop};d.prototype={width:"auto",height:"auto",updateOnResize:!0,rowClass:b.noop,rowRenderer:null,rowClick:function(a){this.editing&&this.editItem(b(a.event.target).closest("tr"))},rowDoubleClick:b.noop,noDataContent:"Not found",noDataRowClass:"jsgrid-nodata-row",heading:!0,headerRowRenderer:null,headerRowClass:"jsgrid-header-row",headerCellClass:"jsgrid-header-cell",filtering:!1,filterRowRenderer:null,filterRowClass:"jsgrid-filter-row",inserting:!1,insertRowRenderer:null,insertRowClass:"jsgrid-insert-row",editing:!1,editRowRenderer:null,editRowClass:"jsgrid-edit-row",confirmDeleting:!0,deleteConfirm:"Are you sure?",selecting:!0,selectedRowClass:"jsgrid-selected-row",oddRowClass:"jsgrid-row",evenRowClass:"jsgrid-alt-row",cellClass:"jsgrid-cell",sorting:!1,sortableClass:"jsgrid-header-sortable",sortAscClass:"jsgrid-header-sort jsgrid-header-sort-asc",sortDescClass:"jsgrid-header-sort jsgrid-header-sort-desc",paging:!1,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",pagerNavButtonInactiveClass:"jsgrid-pager-nav-inactive-button",pageClass:"jsgrid-pager-page",currentPageClass:"jsgrid-pager-current-page",customLoading:!1,pageLoading:!1,autoload:!1,controller:v,loadIndication:!0,loadIndicationDelay:500,loadMessage:"Please, wait...",loadShading:!0,invalidMessage:"Invalid data entered!",invalidNotify:function(c){var d=b.map(c.errors,function(a){return a.message||null});a.alert([this.invalidMessage].concat(d).join("\n"))},onInit:b.noop,onRefreshing:b.noop,onRefreshed:b.noop,onPageChanged:b.noop,onItemDeleting:b.noop,onItemDeleted:b.noop,onItemInserting:b.noop,onItemInserted:b.noop,onItemEditing:b.noop,onItemUpdating:b.noop,onItemUpdated:b.noop,onItemInvalid:b.noop,onDataLoading:b.noop,onDataLoaded:b.noop,onOptionChanging:b.noop,onOptionChanged:b.noop,onError:b.noop,invalidClass:"jsgrid-invalid",containerClass:"jsgrid",tableClass:"jsgrid-table",gridHeaderClass:"jsgrid-grid-header",gridBodyClass:"jsgrid-grid-body",_init:function(a){b.extend(this,a),this._initLoadStrategy(),this._initController(),this._initFields(),this._attachWindowLoadResize(),this._attachWindowResizeCallback(),this._callEventHandler(this.onInit)},loadStrategy:function(){return this.pageLoading?new jsGrid.loadStrategies.PageLoadingStrategy(this):new jsGrid.loadStrategies.DirectLoadingStrategy(this)},_initLoadStrategy:function(){this._loadStrategy=t(this.loadStrategy,this)},_initController:function(){this._controller=b.extend({},v,t(this.controller,this))},renderTemplate:function(a,b,d){args=[];for(var e in d)args.push(d[e]);return args.unshift(a,b),a=t.apply(null,args),a===c||null===a?"":a},loadIndicator:function(a){return new jsGrid.LoadIndicator(a)},validation:function(a){return jsGrid.Validation&&new jsGrid.Validation(a)},_initFields:function(){var a=this;a.fields=b.map(a.fields,function(c){if(b.isPlainObject(c)){var d=c.type&&jsGrid.fields[c.type]||jsGrid.Field;c=new d(c)}return c._grid=a,c})},_attachWindowLoadResize:function(){b(a).on("load",b.proxy(this._refreshSize,this))},_attachWindowResizeCallback:function(){this.updateOnResize&&b(a).on("resize",b.proxy(this._refreshSize,this))},_detachWindowResizeCallback:function(){b(a).off("resize",this._refreshSize)},option:function(a,b){var c,d;return 1===arguments.length?this[a]:(c={option:a,oldValue:this[a],newValue:b},this._callEventHandler(this.onOptionChanging,c),this._handleOptionChange(c.option,c.newValue),d={option:c.option,value:c.newValue},void this._callEventHandler(this.onOptionChanged,d))},fieldOption:function(a,b,c){return a=this._normalizeField(a),2===arguments.length?a[b]:(a[b]=c,void this._renderGrid())},_handleOptionChange:function(a,b){switch(this[a]=b,a){case"width":case"height":this._refreshSize();break;case"rowClass":case"rowRenderer":case"rowClick":case"rowDoubleClick":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":case"pagerRenderer":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"loadStrategy":case"pageLoading":this._initLoadStrategy(),this.search();break;case"pageIndex":this.openPage(b);break;case"pageSize":this.refresh(),this.search();break;case"editRowRenderer":case"editRowClass":this.cancelEdit();break;case"updateOnResize":this._detachWindowResizeCallback(),this._attachWindowResizeCallback();break;case"invalidNotify":case"invalidMessage":break;default:this.render()}},destroy:function(){this._detachWindowResizeCallback(),this._clear(),this._container.removeData(f)},render:function(){return this._renderGrid(),this.autoload?this.loadData():b.Deferred().resolve().promise()},_renderGrid: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._validation=this._createValidation(),this.refresh()},_createLoadIndicator:function(){return t(this.loadIndicator,this,{message:this.loadMessage,shading:this.loadShading,container:this._container})},_createValidation:function(){return t(this.validation,this)},_clear:function(){this.cancelEdit(),clearTimeout(this._loadingTimer),this._pagerContainer&&this._pagerContainer.empty(),this._container.empty().css({position:"",width:"",height:""})},_createHeader:function(){var a=this._headerRow=this._createHeaderRow(),c=this._filterRow=this._createFilterRow(),d=this._insertRow=this._createInsertRow(),e=this._headerGrid=b("<table>").addClass(this.tableClass).append(a).append(c).append(d),f=this._header=b("<div>").addClass(this.gridHeaderClass).addClass(this._scrollBarWidth()?"jsgrid-header-scrollbar":"").append(e);return f},_createBody:function(){var a=this._content=b("<tbody>"),c=this._bodyGrid=b("<table>").addClass(this.tableClass).append(a),d=this._body=b("<div>").addClass(this.gridBodyClass).append(c).on("scroll",b.proxy(function(a){this._header.scrollLeft(a.target.scrollLeft)},this));return d},_createPagerContainer:function(){var a=this.pagerContainer||b("<div>").appendTo(this._container);return b(a).addClass(this.pagerContainerClass)},_eachField:function(a){var c=this;b.each(this.fields,function(b,d){d.visible&&a.call(c,d,b)})},_createHeaderRow:function(){if(b.isFunction(this.headerRowRenderer))return b(this.renderTemplate(this.headerRowRenderer,this));var a=b("<tr>").addClass(this.headerRowClass);return this._eachField(function(c,d){var e=this._prepareCell("<th>",c,"headercss",this.headerCellClass).append(this.renderTemplate(c.headerTemplate,c)).appendTo(a);this.sorting&&c.sorting&&e.addClass(this.sortableClass).on("click",b.proxy(function(){this.sort(d)},this))}),a},_prepareCell:function(a,c,d,e){return b(a).css("width",c.width).addClass(e||this.cellClass).addClass(d&&c[d]||c.css).addClass(c.align?"jsgrid-align-"+c.align:"")},_createFilterRow:function(){if(b.isFunction(this.filterRowRenderer))return b(this.renderTemplate(this.filterRowRenderer,this));var a=b("<tr>").addClass(this.filterRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"filtercss").append(this.renderTemplate(b.filterTemplate,b)).appendTo(a)}),a},_createInsertRow:function(){if(b.isFunction(this.insertRowRenderer))return b(this.renderTemplate(this.insertRowRenderer,this));var a=b("<tr>").addClass(this.insertRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"insertcss").append(this.renderTemplate(b.insertTemplate,b)).appendTo(a)}),a},_callEventHandler:function(a,c){return a.call(this,b.extend(c,{grid:this})),c},reset:function(){return this._resetSorting(),this._resetPager(),this._loadStrategy.reset()},_resetPager:function(){this._firstDisplayingPage=1,this._setPage(1)},_resetSorting:function(){this._sortField=null,this._sortOrder=i,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 a=this._content;if(a.empty(),!this.data.length)return a.append(this._createNoDataRow()),this;for(var b=this._loadStrategy.firstDisplayIndex(),c=this._loadStrategy.lastDisplayIndex(),d=b;c>d;d++){var e=this.data[d];a.append(this._createRow(e,d))}},_createNoDataRow:function(){var a=0;return this._eachField(function(){a++}),b("<tr>").addClass(this.noDataRowClass).append(b("<td>").addClass(this.cellClass).attr("colspan",a).append(this.renderTemplate(this.noDataContent,this)))},_createRow:function(a,c){var d;return b.isFunction(this.rowRenderer)?d=this.renderTemplate(this.rowRenderer,this,{item:a,itemIndex:c}):(d=b("<tr>"),this._renderCells(d,a)),d.addClass(this._getRowClasses(a,c)).data(g,a).on("click",b.proxy(function(b){this.rowClick({item:a,itemIndex:c,event:b})},this)).on("dblclick",b.proxy(function(b){this.rowDoubleClick({item:a,itemIndex:c,event:b})},this)),this.selecting&&this._attachRowHover(d),d},_getRowClasses:function(a,b){var c=[];return c.push((b+1)%2?this.oddRowClass:this.evenRowClass),c.push(t(this.rowClass,this,a,b)),c.join(" ")},_attachRowHover:function(a){var c=this.selectedRowClass;a.hover(function(){b(this).addClass(c)},function(){b(this).removeClass(c)})},_renderCells:function(a,b){return this._eachField(function(c){a.append(this._createCell(b,c))}),this},_createCell:function(a,c){var d,e=this._getItemFieldValue(a,c),f={value:e,item:a};return d=b.isFunction(c.cellRenderer)?this.renderTemplate(c.cellRenderer,c,f):b("<td>").append(this.renderTemplate(c.itemTemplate||e,c,f)),this._prepareCell(d,c)},_getItemFieldValue:function(a,b){for(var c=b.name.split("."),d=a[c.shift()];d&&c.length;)d=d[c.shift()];return d},_setItemFieldValue:function(a,b,c){for(var d=b.name.split("."),e=a,f=d[0];e&&d.length;)a=e,f=d.shift(),e=a[f];if(!e)for(;d.length;)a=a[f]={},f=d.shift();a[f]=c},sort:function(a,c){return b.isPlainObject(a)&&(c=a.order,a=a.field),this._clearSortingCss(),this._setSortingParams(a,c),this._setSortingCss(),this._loadStrategy.sort()},_clearSortingCss:function(){this._headerRow.find("th").removeClass(this.sortAscClass).removeClass(this.sortDescClass)},_setSortingParams:function(a,b){a=this._normalizeField(a),b=b||(this._sortField===a?this._reversedSortOrder(this._sortOrder):i),this._sortField=a,this._sortOrder=b},_normalizeField:function(a){return b.isNumeric(a)?this.fields[a]:"string"==typeof a?b.grep(this.fields,function(b){return b.name===a})[0]:a},_reversedSortOrder:function(a){return a===i?j:i},_setSortingCss:function(){var a=this._visibleFieldIndex(this._sortField);this._headerRow.find("th").eq(a).addClass(this._sortOrder===i?this.sortAscClass:this.sortDescClass)},_visibleFieldIndex:function(a){return b.inArray(a,b.grep(this.fields,function(a){return a.visible}))},_sortData:function(){var a=this._sortFactor(),b=this._sortField;b&&this.data.sort(function(c,d){return a*b.sortingFunc(c[b.name],d[b.name])})},_sortFactor:function(){return this._sortOrder===i?1:-1},_itemsCount:function(){return this._loadStrategy.itemsCount()},_pagesCount:function(){var a=this._itemsCount(),b=this.pageSize;return Math.floor(a/b)+(a%b?1:0)},_refreshPager:function(){var a=this._pagerContainer;a.empty(),this.paging&&a.append(this._createPager());var b=this.paging&&this._pagesCount()>1;a.toggle(b)},_createPager:function(){var a;return a=b.isFunction(this.pagerRenderer)?b(this.pagerRenderer({pageIndex:this.pageIndex,pageCount:this._pagesCount()})):b("<div>").append(this._createPagerByFormat()),a.addClass(this.pagerClass),a},_createPagerByFormat:function(){var a=this.pageIndex,c=this._pagesCount(),d=this._itemsCount(),e=this.pagerFormat.split(" ");return b.map(e,b.proxy(function(e){var f=e;return e===l?f=this._createPages():e===k?f=this._createPagerNavButton(this.pageFirstText,1,a>1):e===m?f=this._createPagerNavButton(this.pagePrevText,a-1,a>1):e===n?f=this._createPagerNavButton(this.pageNextText,a+1,c>a):e===o?f=this._createPagerNavButton(this.pageLastText,c,c>a):e===p?f=a:e===q?f=c:e===r&&(f=d),b.isArray(f)?f.concat([" "]):[f," "]},this))},_createPages:function(){var a=this._pagesCount(),b=this.pageButtonCount,c=this._firstDisplayingPage,d=[];c>1&&d.push(this._createPagerPageNavButton(this.pageNavigatorPrevText,this.showPrevPages));for(var e=0,f=c;b>e&&a>=f;e++,f++)d.push(f===this.pageIndex?this._createPagerCurrentPage():this._createPagerPage(f));return a>c+b-1&&d.push(this._createPagerPageNavButton(this.pageNavigatorNextText,this.showNextPages)),d},_createPagerNavButton:function(a,c,d){return this._createPagerButton(a,this.pagerNavButtonClass+(d?"":" "+this.pagerNavButtonInactiveClass),d?function(){this.openPage(c)}:b.noop)},_createPagerPageNavButton:function(a,b){return this._createPagerButton(a,this.pagerNavButtonClass,b)},_createPagerPage:function(a){return this._createPagerButton(a,this.pageClass,function(){this.openPage(a)})},_createPagerButton:function(a,c,d){var e=b("<a>").attr("href",s).html(a).on("click",b.proxy(d,this));return b("<span>").addClass(c).append(e)},_createPagerCurrentPage:function(){return b("<span>").addClass(this.pageClass).addClass(this.currentPageClass).text(this.pageIndex)},_refreshSize:function(){this._refreshHeight(),this._refreshWidth()},_refreshWidth:function(){var a="auto"===this.width?this._getAutoWidth():this.width;this._container.width(a)},_getAutoWidth:function(){var a=this._headerGrid,b=this._header;a.width("auto");var c=a.outerWidth(),d=b.outerWidth()-b.innerWidth();return a.width(""),c+d},_scrollBarWidth:function(){var a;return function(){if(a===c){var d=b("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"),e=b("<div style='height:100px;'></div>");d.append(e).appendTo("body");var f=e.innerWidth();d.css("overflow-y","auto");var g=e.innerWidth();d.remove(),a=f-g}return a}}(),_refreshHeight:function(){var a,b=this._container,c=this._pagerContainer,d=this.height;b.height(d),"auto"!==d&&(d=b.height(),a=this._header.outerHeight(!0),c.parents(b).length&&(a+=c.outerHeight(!0)),this._body.outerHeight(d-a))},showPrevPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount;this._firstDisplayingPage=a>b?a-b:1,this._refreshPager()},showNextPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount,c=this._pagesCount();this._firstDisplayingPage=a+2*b>c?c-b+1:a+b,this._refreshPager()},openPage:function(a){1>a||a>this._pagesCount()||(this._setPage(a),this._loadStrategy.openPage(a))},_setPage:function(a){var b=this._firstDisplayingPage,c=this.pageButtonCount;this.pageIndex=a,b>a&&(this._firstDisplayingPage=a),a>b+c-1&&(this._firstDisplayingPage=a-c+1),this._callEventHandler(this.onPageChanged,{pageIndex:a})},_controllerCall:function(a,c,d,e){if(d)return b.Deferred().reject().promise();this._showLoading();var f=this._controller;if(!f||!f[a])throw Error("controller has no method '"+a+"'");return u(f[a](c)).done(b.proxy(e,this)).fail(b.proxy(this._errorHandler,this)).always(b.proxy(this._hideLoading,this))},_errorHandler:function(){this._callEventHandler(this.onError,{args:b.makeArray(arguments)})},_showLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadingTimer=setTimeout(b.proxy(function(){this._loadIndicator.show()},this),this.loadIndicationDelay))},_hideLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadIndicator.hide())},search:function(a){return this._resetSorting(),this._resetPager(),this.loadData(a)},loadData:function(a){a=a||(this.filtering?this.getFilter():{}),b.extend(a,this._loadStrategy.loadParams(),this._sortingParams());var c=this._callEventHandler(this.onDataLoading,{filter:a});return this._controllerCall("loadData",a,c.cancel,function(a){a&&(this._loadStrategy.finishLoad(a),this._callEventHandler(this.onDataLoaded,{data:a}))})},getFilter:function(){var a={};return this._eachField(function(b){b.filtering&&this._setItemFieldValue(a,b,b.filterValue())}),a},_sortingParams:function(){return this.sorting&&this._sortField?{sortField:this._sortField.name,sortOrder:this._sortOrder}:{}},getSorting:function(){var a=this._sortingParams();return{field:a.sortField,order:a.sortOrder}},clearFilter:function(){var a=this._createFilterRow();return this._filterRow.replaceWith(a),this._filterRow=a,this.search()},insertItem:function(a){var c=a||this._getValidatedInsertItem();if(!c)return b.Deferred().reject().promise();var d=this._callEventHandler(this.onItemInserting,{item:c});return this._controllerCall("insertItem",c,d.cancel,function(a){a=a||c,this._loadStrategy.finishInsert(a),this._callEventHandler(this.onItemInserted,{item:a})})},_getValidatedInsertItem:function(){var a=this._getInsertItem();return this._validateItem(a,this._insertRow)?a:null},_getInsertItem:function(){var a={};return this._eachField(function(b){b.inserting&&this._setItemFieldValue(a,b,b.insertValue())}),a},_validateItem:function(a,c){var d=[],e={item:a,itemIndex:this._rowIndex(c),row:c};if(this._eachField(function(f){if(f.validate&&(c!==this._insertRow||f.inserting)&&(c!==this._getEditRow()||f.editing)){var g=this._getItemFieldValue(a,f),h=this._validation.validate(b.extend({value:g,rules:f.validate},e));this._setCellValidity(c.children().eq(this._visibleFieldIndex(f)),h),h.length&&d.push.apply(d,b.map(h,function(a){return{field:f,message:a}}))}}),!d.length)return!0;var f=b.extend({errors:d},e);return this._callEventHandler(this.onItemInvalid,f),this.invalidNotify(f),!1},_setCellValidity:function(a,b){a.toggleClass(this.invalidClass,!!b.length).attr("title",b.join("\n"))},clearInsert:function(){var a=this._createInsertRow();this._insertRow.replaceWith(a),this._insertRow=a,this.refresh()},editItem:function(a){var b=this.rowByItem(a);b.length&&this._editRow(b)},rowByItem:function(a){return a.jquery||a.nodeType?b(a):this._content.find("tr").filter(function(){return b.data(this,g)===a})},_editRow:function(a){if(this.editing){var b=a.data(g),c=this._callEventHandler(this.onItemEditing,{row:a,item:b,itemIndex:this._itemIndex(b)});if(!c.cancel){this._editingRow&&this.cancelEdit();var d=this._createEditRow(b);this._editingRow=a,a.hide(),d.insertBefore(a),a.data(h,d)}}},_createEditRow:function(a){if(b.isFunction(this.editRowRenderer))return b(this.renderTemplate(this.editRowRenderer,this,{item:a,itemIndex:this._itemIndex(a)}));var c=b("<tr>").addClass(this.editRowClass);return this._eachField(function(b){var d=this._getItemFieldValue(a,b);this._prepareCell("<td>",b,"editcss").append(this.renderTemplate(b.editTemplate||"",b,{value:d,item:a})).appendTo(c)}),c},updateItem:function(a,b){1===arguments.length&&(b=a);var c=a?this.rowByItem(a):this._editingRow;return(b=b||this._getValidatedEditedItem())?this._updateRow(c,b):void 0},_getValidatedEditedItem:function(){var a=this._getEditedItem();return this._validateItem(a,this._getEditRow())?a:null},_updateRow:function(a,c){var d=a.data(g),e=this._itemIndex(d),f=b.extend(!0,{},d,c),h=this._callEventHandler(this.onItemUpdating,{row:a,item:f,itemIndex:e,previousItem:d});return this._controllerCall("updateItem",f,h.cancel,function(g){var h=b.extend(!0,{},d);f=g||b.extend(!0,d,c);var i=this._finishUpdate(a,f,e);this._callEventHandler(this.onItemUpdated,{row:i,item:f,itemIndex:e,previousItem:h})})},_rowIndex:function(a){return this._content.children().index(b(a))},_itemIndex:function(a){return b.inArray(a,this.data)},_finishUpdate:function(a,b,c){this.cancelEdit(),this.data[c]=b;var d=this._createRow(b,c);return a.replaceWith(d),d},_getEditedItem:function(){var a={};return this._eachField(function(b){b.editing&&this._setItemFieldValue(a,b,b.editValue())}),a},cancelEdit:function(){this._editingRow&&(this._getEditRow().remove(),this._editingRow.show(),this._editingRow=null)},_getEditRow:function(){return this._editingRow&&this._editingRow.data(h)},deleteItem:function(b){var c=this.rowByItem(b);if(c.length&&(!this.confirmDeleting||a.confirm(t(this.deleteConfirm,this,c.data(g)))))return this._deleteRow(c)},_deleteRow:function(a){var b=a.data(g),c=this._itemIndex(b),d=this._callEventHandler(this.onItemDeleting,{row:a,item:b,itemIndex:c});return this._controllerCall("deleteItem",b,d.cancel,function(){this._loadStrategy.finishDelete(b,c),this._callEventHandler(this.onItemDeleted,{row:a,item:b,itemIndex:c})})}},b.fn.jsGrid=function(a){var e=b.makeArray(arguments),g=e.slice(1),h=this;return this.each(function(){var e,i=b(this),j=i.data(f);if(j)if("string"==typeof a){if(e=j[a].apply(j,g),e!==c&&e!==j)return h=e,!1}else j._detachWindowResizeCallback(),j._init(a),j.render();else new d(i,a)}),h};var w={},x=function(a){var c;b.isPlainObject(a)?c=d.prototype:(c=w[a].prototype,a=arguments[1]||{}),b.extend(c,a)},y={},z=function(a){var c=b.isPlainObject(a)?a:y[a];if(!c)throw Error("unknown locale "+a);A(jsGrid,c)},A=function(a,c){b.each(c,function(c,d){return b.isPlainObject(d)?void A(a[c]||a[c[0].toUpperCase()+c.slice(1)],d):void(a.hasOwnProperty(c)?a[c]=d:a.prototype[c]=d)})};a.jsGrid={Grid:d,fields:w,setDefaults:x,locales:y,locale:z,version:"1.5.3"}}(window,jQuery),function(a,b){function c(a){this._init(a)}c.prototype={container:"body",message:"Loading...",shading:!0,zIndex:1e3,shaderClass:"jsgrid-load-shader",loadPanelClass:"jsgrid-load-panel",_init:function(a){b.extend(!0,this,a),this._initContainer(),this._initShader(),this._initLoadPanel()},_initContainer:function(){this._container=b(this.container)},_initShader:function(){this.shading&&(this._shader=b("<div>").addClass(this.shaderClass).hide().css({position:"absolute",top:0,right:0,bottom:0,left:0,zIndex:this.zIndex}).appendTo(this._container))},_initLoadPanel:function(){this._loadPanel=b("<div>").addClass(this.loadPanelClass).text(this.message).hide().css({position:"absolute",top:"50%",left:"50%",zIndex:this.zIndex}).appendTo(this._container)},show:function(){var a=this._loadPanel.show(),b=a.outerWidth(),c=a.outerHeight();a.css({marginTop:-c/2,marginLeft:-b/2}),this._shader.show()},hide:function(){this._loadPanel.hide(),this._shader.hide()}},a.LoadIndicator=c}(jsGrid,jQuery),function(a,b){function c(a){this._grid=a}function d(a){this._grid=a,this._itemsCount=0}c.prototype={firstDisplayIndex:function(){var a=this._grid;return a.option("paging")?(a.option("pageIndex")-1)*a.option("pageSize"):0},lastDisplayIndex:function(){var a=this._grid,b=a.option("data").length;return a.option("paging")?Math.min(a.option("pageIndex")*a.option("pageSize"),b):b},itemsCount:function(){return this._grid.option("data").length},openPage:function(){this._grid.refresh()},loadParams:function(){return{}},sort:function(){return this._grid._sortData(),this._grid.refresh(),b.Deferred().resolve().promise()},reset:function(){return this._grid.refresh(),b.Deferred().resolve().promise()},finishLoad:function(a){this._grid.option("data",a)},finishInsert:function(a){var b=this._grid;b.option("data").push(a),b.refresh()},finishDelete:function(a,b){var c=this._grid;c.option("data").splice(b,1),c.reset()}},d.prototype={firstDisplayIndex:function(){return 0},lastDisplayIndex:function(){return this._grid.option("data").length},itemsCount:function(){return this._itemsCount},openPage:function(){this._grid.loadData()},loadParams:function(){var a=this._grid;return{pageIndex:a.option("pageIndex"),pageSize:a.option("pageSize")}},reset:function(){return this._grid.loadData()},sort:function(){return this._grid.loadData()},finishLoad:function(a){this._itemsCount=a.itemsCount,this._grid.option("data",a.data)},finishInsert:function(){this._grid.search()},finishDelete:function(){this._grid.search()}},a.loadStrategies={DirectLoadingStrategy:c,PageLoadingStrategy:d}}(jsGrid,jQuery),function(a){var b=function(a){return"undefined"!=typeof a&&null!==a},c={string:function(a,c){return b(a)||b(c)?b(a)?b(c)?(""+a).localeCompare(""+c):1:-1:0},number:function(a,b){return a-b},date:function(a,b){return a-b},numberAsString:function(a,b){return parseFloat(a)-parseFloat(b)}};a.sortStrategies=c}(jsGrid,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={_init:function(a){b.extend(!0,this,a)},validate:function(a){var c=[];return b.each(this._normalizeRules(a.rules),function(d,e){if(!e.validator(a.value,a.item,e.param)){var f=b.isFunction(e.message)?e.message(a.value,a.item):e.message;c.push(f)}}),c},_normalizeRules:function(a){return b.isArray(a)||(a=[a]),b.map(a,b.proxy(function(a){return this._normalizeRule(a)},this))},_normalizeRule:function(a){if("string"==typeof a&&(a={validator:a}),b.isFunction(a)&&(a={validator:a}),!b.isPlainObject(a))throw Error("wrong validation config specified");return a=b.extend({},a),b.isFunction(a.validator)?a:this._applyNamedValidator(a,a.validator)},_applyNamedValidator:function(a,c){delete a.validator;var d=e[c];if(!d)throw Error('unknown validator "'+c+'"');return b.isFunction(d)&&(d={validator:d}),b.extend({},d,a)}},a.Validation=d;var e={required:{message:"Field is required",validator:function(a){return a!==c&&null!==a&&""!==a}},rangeLength:{message:"Field value length is out of the defined range",validator:function(a,b,c){return a.length>=c[0]&&a.length<=c[1]}},minLength:{message:"Field value is too short",validator:function(a,b,c){return a.length>=c}},maxLength:{message:"Field value is too long",validator:function(a,b,c){return a.length<=c}},pattern:{message:"Field value is not matching the defined pattern",validator:function(a,b,c){return"string"==typeof c&&(c=new RegExp("^(?:"+c+")$")),c.test(a)}},range:{message:"Field value is out of the defined range",validator:function(a,b,c){return a>=c[0]&&a<=c[1]}},min:{message:"Field value is too small",validator:function(a,b,c){return a>=c}},max:{message:"Field value is too large",validator:function(a,b,c){return c>=a}}};a.validators=e}(jsGrid,jQuery),function(a,b,c){function d(a){b.extend(!0,this,a),this.sortingFunc=this._getSortingFunc()}d.prototype={name:"",title:null,css:"",align:"",width:100,visible:!0,filtering:!0,inserting:!0,editing:!0,sorting:!0,sorter:"string",headerTemplate:function(){return this.title===c||null===this.title?this.name:this.title},itemTemplate:function(a){return a},filterTemplate:function(){return""},insertTemplate:function(){return""},editTemplate:function(a,b){return this._value=a,this.itemTemplate(a,b)},filterValue:function(){return""},insertValue:function(){return""},editValue:function(){return this._value},_getSortingFunc:function(){var c=this.sorter;if(b.isFunction(c))return c;if("string"==typeof c)return a.sortStrategies[c];throw Error('wrong sorter for the field "'+this.name+'"!')}},a.Field=d}(jsGrid,jQuery),function(a,b){function c(a){d.call(this,a)}var d=a.Field;c.prototype=new d({autosearch:!0,readOnly:!1,filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createTextBox();return this.autosearch&&b.on("keypress",function(b){13===b.which&&(a.search(),b.preventDefault())}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createTextBox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextBox();return b.val(a),b},filterValue:function(){return this.filterControl.val()},insertValue:function(){return this.insertControl.val()},editValue:function(){return this.editControl.val()},_createTextBox:function(){return b("<input>").attr("type","text").prop("readonly",!!this.readOnly)}}),a.fields.text=a.TextField=c}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({sorter:"number",align:"right",readOnly:!1,filterValue:function(){return this.filterControl.val()?parseInt(this.filterControl.val()||0,10):c},insertValue:function(){return this.insertControl.val()?parseInt(this.insertControl.val()||0,10):c},editValue:function(){return this.editControl.val()?parseInt(this.editControl.val()||0,10):c},_createTextBox:function(){return b("<input>").attr("type","number").prop("readonly",!!this.readOnly)}}),a.fields.number=a.NumberField=d}(jsGrid,jQuery),function(a,b){function c(a){d.call(this,a)}var d=a.TextField;c.prototype=new d({insertTemplate:function(){return this.inserting?this.insertControl=this._createTextArea():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextArea();return b.val(a),b},_createTextArea:function(){return b("<textarea>").prop("readonly",!!this.readOnly)}}),a.fields.textarea=a.TextAreaField=c}(jsGrid,jQuery),function(a,b,c){function d(a){if(this.items=[],this.selectedIndex=-1,this.valueField="",this.textField="",a.valueField&&a.items.length){var b=a.items[0][a.valueField];this.valueType=typeof b===f?f:g}this.sorter=this.valueType,e.call(this,a)}var e=a.NumberField,f="number",g="string";d.prototype=new e({align:"center",valueType:f,itemTemplate:function(a){var d,e=this.items,f=this.valueField,g=this.textField;d=f?b.grep(e,function(b){return b[f]===a})[0]||{}:e[a];var h=g?d[g]:d;return h===c||null===h?"":h},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createSelect();return this.autosearch&&b.on("change",function(){a.search()}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createSelect():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createSelect();return a!==c&&b.val(a),b},filterValue:function(){var a=this.filterControl.val();return this.valueType===f?parseInt(a||0,10):a},insertValue:function(){var a=this.insertControl.val();return this.valueType===f?parseInt(a||0,10):a},editValue:function(){var a=this.editControl.val();return this.valueType===f?parseInt(a||0,10):a},_createSelect:function(){var a=b("<select>"),c=this.valueField,d=this.textField,e=this.selectedIndex;return b.each(this.items,function(f,g){var h=c?g[c]:f,i=d?g[d]:g,j=b("<option>").attr("value",h).text(i).appendTo(a);j.prop("selected",e===f)}),a.prop("disabled",!!this.readOnly),a}}),a.fields.select=a.SelectField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({sorter:"number",align:"center",autosearch:!0,itemTemplate:function(a){return this._createCheckbox().prop({checked:a,disabled:!0})},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,c=this.filterControl=this._createCheckbox();return c.prop({readOnly:!0,indeterminate:!0}),c.on("click",function(){var a=b(this); +a.prop("readOnly")?a.prop({checked:!1,readOnly:!1}):a.prop("checked")||a.prop({readOnly:!0,indeterminate:!0})}),this.autosearch&&c.on("click",function(){a.search()}),c},insertTemplate:function(){return this.inserting?this.insertControl=this._createCheckbox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createCheckbox();return b.prop("checked",a),b},filterValue:function(){return this.filterControl.get(0).indeterminate?c:this.filterControl.is(":checked")},insertValue:function(){return this.insertControl.is(":checked")},editValue:function(){return this.editControl.is(":checked")},_createCheckbox:function(){return b("<input>").attr("type","checkbox")}}),a.fields.checkbox=a.CheckboxField=d}(jsGrid,jQuery),function(a,b){function c(a){d.call(this,a),this._configInitialized=!1}var d=a.Field;c.prototype=new d({css:"jsgrid-control-field",align:"center",width:50,filtering:!1,inserting:!1,editing:!1,sorting:!1,buttonClass:"jsgrid-button",modeButtonClass:"jsgrid-mode-button",modeOnButtonClass:"jsgrid-mode-on-button",searchModeButtonClass:"jsgrid-search-mode-button",insertModeButtonClass:"jsgrid-insert-mode-button",editButtonClass:"jsgrid-edit-button",deleteButtonClass:"jsgrid-delete-button",searchButtonClass:"jsgrid-search-button",clearFilterButtonClass:"jsgrid-clear-filter-button",insertButtonClass:"jsgrid-insert-button",updateButtonClass:"jsgrid-update-button",cancelEditButtonClass:"jsgrid-cancel-edit-button",searchModeButtonTooltip:"Switch to searching",insertModeButtonTooltip:"Switch to inserting",editButtonTooltip:"Edit",deleteButtonTooltip:"Delete",searchButtonTooltip:"Search",clearFilterButtonTooltip:"Clear filter",insertButtonTooltip:"Insert",updateButtonTooltip:"Update",cancelEditButtonTooltip:"Cancel edit",editButton:!0,deleteButton:!0,clearFilterButton:!0,modeSwitchButton:!0,_initConfig:function(){this._hasFiltering=this._grid.filtering,this._hasInserting=this._grid.inserting,this._hasInserting&&this.modeSwitchButton&&(this._grid.inserting=!1),this._configInitialized=!0},headerTemplate:function(){this._configInitialized||this._initConfig();var a=this._hasFiltering,b=this._hasInserting;return this.modeSwitchButton&&(a||b)?a&&!b?this._createFilterSwitchButton():b&&!a?this._createInsertSwitchButton():this._createModeSwitchButton():""},itemTemplate:function(a,c){var d=b([]);return this.editButton&&(d=d.add(this._createEditButton(c))),this.deleteButton&&(d=d.add(this._createDeleteButton(c))),d},filterTemplate:function(){var a=this._createSearchButton();return this.clearFilterButton?a.add(this._createClearFilterButton()):a},insertTemplate:function(){return this._createInsertButton()},editTemplate:function(){return this._createUpdateButton().add(this._createCancelEditButton())},_createFilterSwitchButton:function(){return this._createOnOffSwitchButton("filtering",this.searchModeButtonClass,!0)},_createInsertSwitchButton:function(){return this._createOnOffSwitchButton("inserting",this.insertModeButtonClass,!1)},_createOnOffSwitchButton:function(a,c,d){var e=d,f=b.proxy(function(){g.toggleClass(this.modeOnButtonClass,e)},this),g=this._createGridButton(this.modeButtonClass+" "+c,"",function(b){e=!e,b.option(a,e),f()});return f(),g},_createModeSwitchButton:function(){var a=!1,c=b.proxy(function(){d.attr("title",a?this.searchModeButtonTooltip:this.insertModeButtonTooltip).toggleClass(this.insertModeButtonClass,!a).toggleClass(this.searchModeButtonClass,a)},this),d=this._createGridButton(this.modeButtonClass,"",function(b){a=!a,b.option("inserting",a),b.option("filtering",!a),c()});return c(),d},_createEditButton:function(a){return this._createGridButton(this.editButtonClass,this.editButtonTooltip,function(b,c){b.editItem(a),c.stopPropagation()})},_createDeleteButton:function(a){return this._createGridButton(this.deleteButtonClass,this.deleteButtonTooltip,function(b,c){b.deleteItem(a),c.stopPropagation()})},_createSearchButton:function(){return this._createGridButton(this.searchButtonClass,this.searchButtonTooltip,function(a){a.search()})},_createClearFilterButton:function(){return this._createGridButton(this.clearFilterButtonClass,this.clearFilterButtonTooltip,function(a){a.clearFilter()})},_createInsertButton:function(){return this._createGridButton(this.insertButtonClass,this.insertButtonTooltip,function(a){a.insertItem().done(function(){a.clearInsert()})})},_createUpdateButton:function(){return this._createGridButton(this.updateButtonClass,this.updateButtonTooltip,function(a,b){a.updateItem(),b.stopPropagation()})},_createCancelEditButton:function(){return this._createGridButton(this.cancelEditButtonClass,this.cancelEditButtonTooltip,function(a,b){a.cancelEdit(),b.stopPropagation()})},_createGridButton:function(a,c,d){var e=this._grid;return b("<input>").addClass(this.buttonClass).addClass(a).attr({type:"button",title:c}).on("click",function(a){d(e,a)})},editValue:function(){return""}}),a.fields.control=a.ControlField=c}(jsGrid,jQuery); \ No newline at end of file
3
Brought dist/ back to 1.5.3
2
.js
min
mit
tabalinas/jsgrid
10063493
<NME> jsgrid.min.js <BEF> /* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2017 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ !function(a,b,c){function d(a,c){var d=b(a);d.data(f,this),this._container=d,this.data=[],this.fields=[],this._editingRow=null,this._sortField=null,this._sortOrder=i,this._firstDisplayingPage=1,this._init(c),this.render()}var e="JSGrid",f=e,g="JSGridItem",h="JSGridEditRow",i="asc",j=function(a,c){return b.isFunction(a)?a.apply(c,b.makeArray(arguments).slice(2)):a},k=function(a){var c=b.Deferred();return a&&a.then?a.then(function(){c.resolve.apply(c,arguments)},function(){c.reject.apply(c,arguments)}):c.resolve(a),c.promise()},l={loadData:b.noop,insertItem:b.noop,updateItem:b.noop,deleteItem:b.noop};d.prototype={width:"auto",height:"auto",updateOnResize:!0,rowClass:b.noop,rowRenderer:null,rowClick:function(a){this.editing&&this.editItem(b(a.event.target).closest("tr"))},rowDoubleClick:b.noop,noDataContent:"Not found",noDataRowClass:"jsgrid-nodata-row",heading:!0,headerRowRenderer:null,headerRowClass:"jsgrid-header-row",headerCellClass:"jsgrid-header-cell",filtering:!1,filterRowRenderer:null,filterRowClass:"jsgrid-filter-row",inserting:!1,insertRowLocation:"bottom",insertRowRenderer:null,insertRowClass:"jsgrid-insert-row",editing:!1,editRowRenderer:null,editRowClass:"jsgrid-edit-row",confirmDeleting:!0,deleteConfirm:"Are you sure?",selecting:!0,selectedRowClass:"jsgrid-selected-row",oddRowClass:"jsgrid-row",evenRowClass:"jsgrid-alt-row",cellClass:"jsgrid-cell",sorting:!1,sortableClass:"jsgrid-header-sortable",sortAscClass:"jsgrid-header-sort jsgrid-header-sort-asc",sortDescClass:"jsgrid-header-sort jsgrid-header-sort-desc",paging:!1,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",pagerNavButtonInactiveClass:"jsgrid-pager-nav-inactive-button",pageClass:"jsgrid-pager-page",currentPageClass:"jsgrid-pager-current-page",customLoading:!1,pageLoading:!1,autoload:!1,controller:l,loadIndication:!0,loadIndicationDelay:500,loadMessage:"Please, wait...",loadShading:!0,invalidMessage:"Invalid data entered!",invalidNotify:function(c){var d=b.map(c.errors,function(a){return a.message||null});a.alert([this.invalidMessage].concat(d).join("\n"))},onInit:b.noop,onRefreshing:b.noop,onRefreshed:b.noop,onPageChanged:b.noop,onItemDeleting:b.noop,onItemDeleted:b.noop,onItemInserting:b.noop,onItemInserted:b.noop,onItemEditing:b.noop,onItemEditCancelling:b.noop,onItemUpdating:b.noop,onItemUpdated:b.noop,onItemInvalid:b.noop,onDataLoading:b.noop,onDataLoaded:b.noop,onOptionChanging:b.noop,onOptionChanged:b.noop,onError:b.noop,invalidClass:"jsgrid-invalid",containerClass:"jsgrid",tableClass:"jsgrid-table",gridHeaderClass:"jsgrid-grid-header",gridBodyClass:"jsgrid-grid-body",_init:function(a){b.extend(this,a),this._initLoadStrategy(),this._initController(),this._initFields(),this._attachWindowLoadResize(),this._attachWindowResizeCallback(),this._callEventHandler(this.onInit)},loadStrategy:function(){return this.pageLoading?new jsGrid.loadStrategies.PageLoadingStrategy(this):new jsGrid.loadStrategies.DirectLoadingStrategy(this)},_initLoadStrategy:function(){this._loadStrategy=j(this.loadStrategy,this)},_initController:function(){this._controller=b.extend({},l,j(this.controller,this))},renderTemplate:function(a,b,d){args=[];for(var e in d)args.push(d[e]);return args.unshift(a,b),a=j.apply(null,args),a===c||null===a?"":a},loadIndicator:function(a){return new jsGrid.LoadIndicator(a)},validation:function(a){return jsGrid.Validation&&new jsGrid.Validation(a)},_initFields:function(){var a=this;a.fields=b.map(a.fields,function(c){return b.isPlainObject(c)&&(c=new(c.type&&jsGrid.fields[c.type]||jsGrid.Field)(c)),c._grid=a,c})},_attachWindowLoadResize:function(){b(a).on("load",b.proxy(this._refreshSize,this))},_attachWindowResizeCallback:function(){this.updateOnResize&&b(a).on("resize",b.proxy(this._refreshSize,this))},_detachWindowResizeCallback:function(){b(a).off("resize",this._refreshSize)},option:function(a,b){var c,d;if(1===arguments.length)return this[a];c={option:a,oldValue:this[a],newValue:b},this._callEventHandler(this.onOptionChanging,c),this._handleOptionChange(c.option,c.newValue),d={option:c.option,value:c.newValue},this._callEventHandler(this.onOptionChanged,d)},fieldOption:function(a,b,c){if(a=this._normalizeField(a),2===arguments.length)return a[b];a[b]=c,this._renderGrid()},_handleOptionChange:function(a,b){switch(this[a]=b,a){case"width":case"height":this._refreshSize();break;case"rowClass":case"rowRenderer":case"rowClick":case"rowDoubleClick":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":case"pagerRenderer":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"loadStrategy":case"pageLoading":this._initLoadStrategy(),this.search();break;case"pageIndex":this.openPage(b);break;case"pageSize":this.refresh(),this.search();break;case"editRowRenderer":case"editRowClass":this.cancelEdit();break;case"updateOnResize":this._detachWindowResizeCallback(),this._attachWindowResizeCallback();break;case"invalidNotify":case"invalidMessage":break;default:this.render()}},destroy:function(){this._detachWindowResizeCallback(),this._clear(),this._container.removeData(f)},render:function(){return this._renderGrid(),this.autoload?this.loadData():b.Deferred().resolve().promise()},_renderGrid: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._validation=this._createValidation(),this.refresh()},_createLoadIndicator:function(){return j(this.loadIndicator,this,{message:this.loadMessage,shading:this.loadShading,container:this._container})},_createValidation:function(){return j(this.validation,this)},_clear:function(){this.cancelEdit(),clearTimeout(this._loadingTimer),this._pagerContainer&&this._pagerContainer.empty(),this._container.empty().css({position:"",width:"",height:""})},_createHeader:function(){var a=this._headerRow=this._createHeaderRow(),c=this._filterRow=this._createFilterRow(),d=this._insertRow=this._createInsertRow(),e=this._headerGrid=b("<table>").addClass(this.tableClass).append(a).append(c).append(d);return this._header=b("<div>").addClass(this.gridHeaderClass).addClass(this._scrollBarWidth()?"jsgrid-header-scrollbar":"").append(e)},_createBody:function(){var a=this._content=b("<tbody>"),c=this._bodyGrid=b("<table>").addClass(this.tableClass).append(a);return this._body=b("<div>").addClass(this.gridBodyClass).append(c).on("scroll",b.proxy(function(a){this._header.scrollLeft(a.target.scrollLeft)},this))},_createPagerContainer:function(){return b(this.pagerContainer||b("<div>").appendTo(this._container)).addClass(this.pagerContainerClass)},_eachField:function(a){var c=this;b.each(this.fields,function(b,d){d.visible&&a.call(c,d,b)})},_createHeaderRow:function(){if(b.isFunction(this.headerRowRenderer))return b(this.renderTemplate(this.headerRowRenderer,this));var a=b("<tr>").addClass(this.headerRowClass);return this._eachField(function(c,d){var e=this._prepareCell("<th>",c,"headercss",this.headerCellClass).append(this.renderTemplate(c.headerTemplate,c)).appendTo(a);this.sorting&&c.sorting&&e.addClass(this.sortableClass).on("click",b.proxy(function(){this.sort(d)},this))}),a},_prepareCell:function(a,c,d,e){return b(a).css("width",c.width).addClass(e||this.cellClass).addClass(d&&c[d]||c.css).addClass(c.align?"jsgrid-align-"+c.align:"")},_createFilterRow:function(){if(b.isFunction(this.filterRowRenderer))return b(this.renderTemplate(this.filterRowRenderer,this));var a=b("<tr>").addClass(this.filterRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"filtercss").append(this.renderTemplate(b.filterTemplate,b)).appendTo(a)}),a},_createInsertRow:function(){if(b.isFunction(this.insertRowRenderer))return b(this.renderTemplate(this.insertRowRenderer,this));var a=b("<tr>").addClass(this.insertRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"insertcss").append(this.renderTemplate(b.insertTemplate,b)).appendTo(a)}),a},_callEventHandler:function(a,c){return a.call(this,b.extend(c,{grid:this})),c},reset:function(){return this._resetSorting(),this._resetPager(),this._loadStrategy.reset()},_resetPager:function(){this._firstDisplayingPage=1,this._setPage(1)},_resetSorting:function(){this._sortField=null,this._sortOrder=i,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 a=this._content;if(a.empty(),!this.data.length)return a.append(this._createNoDataRow()),this;for(var b=this._loadStrategy.firstDisplayIndex(),c=this._loadStrategy.lastDisplayIndex(),d=b;d<c;d++){var e=this.data[d];a.append(this._createRow(e,d))}},_createNoDataRow:function(){var a=0;return this._eachField(function(){a++}),b("<tr>").addClass(this.noDataRowClass).append(b("<td>").addClass(this.cellClass).attr("colspan",a).append(this.renderTemplate(this.noDataContent,this)))},_createRow:function(a,c){var d;return b.isFunction(this.rowRenderer)?d=this.renderTemplate(this.rowRenderer,this,{item:a,itemIndex:c}):(d=b("<tr>"),this._renderCells(d,a)),d.addClass(this._getRowClasses(a,c)).data(g,a).on("click",b.proxy(function(b){this.rowClick({item:a,itemIndex:c,event:b})},this)).on("dblclick",b.proxy(function(b){this.rowDoubleClick({item:a,itemIndex:c,event:b})},this)),this.selecting&&this._attachRowHover(d),d},_getRowClasses:function(a,b){var c=[];return c.push((b+1)%2?this.oddRowClass:this.evenRowClass),c.push(j(this.rowClass,this,a,b)),c.join(" ")},_attachRowHover:function(a){var c=this.selectedRowClass;a.hover(function(){b(this).addClass(c)},function(){b(this).removeClass(c)})},_renderCells:function(a,b){return this._eachField(function(c){a.append(this._createCell(b,c))}),this},_createCell:function(a,c){var d,e=this._getItemFieldValue(a,c),f={value:e,item:a};return d=b.isFunction(c.cellRenderer)?this.renderTemplate(c.cellRenderer,c,f):b("<td>").append(this.renderTemplate(c.itemTemplate||e,c,f)),this._prepareCell(d,c)},_getItemFieldValue:function(a,b){for(var c=b.name.split("."),d=a[c.shift()];d&&c.length;)d=d[c.shift()];return d},_setItemFieldValue:function(a,b,c){for(var d=b.name.split("."),e=a,f=d[0];e&&d.length;)a=e,f=d.shift(),e=a[f];if(!e)for(;d.length;)a=a[f]={},f=d.shift();a[f]=c},sort:function(a,c){return b.isPlainObject(a)&&(c=a.order,a=a.field),this._clearSortingCss(),this._setSortingParams(a,c),this._setSortingCss(),this._loadStrategy.sort()},_clearSortingCss:function(){this._headerRow.find("th").removeClass(this.sortAscClass).removeClass(this.sortDescClass)},_setSortingParams:function(a,b){a=this._normalizeField(a),b=b||(this._sortField===a?this._reversedSortOrder(this._sortOrder):i),this._sortField=a,this._sortOrder=b},_normalizeField:function(a){return b.isNumeric(a)?this.fields[a]:"string"==typeof a?b.grep(this.fields,function(b){return b.name===a})[0]:a},_reversedSortOrder:function(a){return a===i?"desc":i},_setSortingCss:function(){var a=this._visibleFieldIndex(this._sortField);this._headerRow.find("th").eq(a).addClass(this._sortOrder===i?this.sortAscClass:this.sortDescClass)},_visibleFieldIndex:function(a){return b.inArray(a,b.grep(this.fields,function(a){return a.visible}))},_sortData:function(){var a=this._sortFactor(),b=this._sortField;b&&this.data.sort(function(c,d){return a*b.sortingFunc(c[b.name],d[b.name])})},_sortFactor:function(){return this._sortOrder===i?1:-1},_itemsCount:function(){return this._loadStrategy.itemsCount()},_pagesCount:function(){var a=this._itemsCount(),b=this.pageSize;return Math.floor(a/b)+(a%b?1:0)},_refreshPager:function(){var a=this._pagerContainer;a.empty(),this.paging&&a.append(this._createPager());var b=this.paging&&this._pagesCount()>1;a.toggle(b)},_createPager:function(){var a;return a=b.isFunction(this.pagerRenderer)?b(this.pagerRenderer({pageIndex:this.pageIndex,pageCount:this._pagesCount()})):b("<div>").append(this._createPagerByFormat()),a.addClass(this.pagerClass),a},_createPagerByFormat:function(){var a=this.pageIndex,c=this._pagesCount(),d=this._itemsCount(),e=this.pagerFormat.split(" ");return b.map(e,b.proxy(function(e){var f=e;return"{pages}"===e?f=this._createPages():"{first}"===e?f=this._createPagerNavButton(this.pageFirstText,1,a>1):"{prev}"===e?f=this._createPagerNavButton(this.pagePrevText,a-1,a>1):"{next}"===e?f=this._createPagerNavButton(this.pageNextText,a+1,a<c):"{last}"===e?f=this._createPagerNavButton(this.pageLastText,c,a<c):"{pageIndex}"===e?f=a:"{pageCount}"===e?f=c:"{itemCount}"===e&&(f=d),b.isArray(f)?f.concat([" "]):[f," "]},this))},_createPages:function(){var a=this._pagesCount(),b=this.pageButtonCount,c=this._firstDisplayingPage,d=[];c>1&&d.push(this._createPagerPageNavButton(this.pageNavigatorPrevText,this.showPrevPages));for(var e=0,f=c;e<b&&f<=a;e++,f++)d.push(f===this.pageIndex?this._createPagerCurrentPage():this._createPagerPage(f));return c+b-1<a&&d.push(this._createPagerPageNavButton(this.pageNavigatorNextText,this.showNextPages)),d},_createPagerNavButton:function(a,c,d){return this._createPagerButton(a,this.pagerNavButtonClass+(d?"":" "+this.pagerNavButtonInactiveClass),d?function(){this.openPage(c)}:b.noop)},_createPagerPageNavButton:function(a,b){return this._createPagerButton(a,this.pagerNavButtonClass,b)},_createPagerPage:function(a){return this._createPagerButton(a,this.pageClass,function(){this.openPage(a)})},_createPagerButton:function(a,c,d){var e=b("<a>").attr("href","javascript:void(0);").html(a).on("click",b.proxy(d,this));return b("<span>").addClass(c).append(e)},_createPagerCurrentPage:function(){return b("<span>").addClass(this.pageClass).addClass(this.currentPageClass).text(this.pageIndex)},_refreshSize:function(){this._refreshHeight(),this._refreshWidth()},_refreshWidth:function(){var a="auto"===this.width?this._getAutoWidth():this.width;this._container.width(a)},_getAutoWidth:function(){var a=this._headerGrid,b=this._header;a.width("auto");var c=a.outerWidth(),d=b.outerWidth()-b.innerWidth();return a.width(""),c+d},_scrollBarWidth:function(){var a;return function(){if(a===c){var d=b("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"),e=b("<div style='height:100px;'></div>");d.append(e).appendTo("body");var f=e.innerWidth();d.css("overflow-y","auto");var g=e.innerWidth();d.remove(),a=f-g}return a}}(),_refreshHeight:function(){var a,b=this._container,c=this._pagerContainer,d=this.height;b.height(d),"auto"!==d&&(d=b.height(),a=this._header.outerHeight(!0),c.parents(b).length&&(a+=c.outerHeight(!0)),this._body.outerHeight(d-a))},showPrevPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount;this._firstDisplayingPage=a>b?a-b:1,this._refreshPager()},showNextPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount,c=this._pagesCount();this._firstDisplayingPage=a+2*b>c?c-b+1:a+b,this._refreshPager()},openPage:function(a){a<1||a>this._pagesCount()||(this._setPage(a),this._loadStrategy.openPage(a))},_setPage:function(a){var b=this._firstDisplayingPage,c=this.pageButtonCount;this.pageIndex=a,a<b&&(this._firstDisplayingPage=a),a>b+c-1&&(this._firstDisplayingPage=a-c+1),this._callEventHandler(this.onPageChanged,{pageIndex:a})},_controllerCall:function(a,c,d,e){if(d)return b.Deferred().reject().promise();this._showLoading();var f=this._controller;if(!f||!f[a])throw Error("controller has no method '"+a+"'");return k(f[a](c)).done(b.proxy(e,this)).fail(b.proxy(this._errorHandler,this)).always(b.proxy(this._hideLoading,this))},_errorHandler:function(){this._callEventHandler(this.onError,{args:b.makeArray(arguments)})},_showLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadingTimer=setTimeout(b.proxy(function(){this._loadIndicator.show()},this),this.loadIndicationDelay))},_hideLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadIndicator.hide())},search:function(a){return this._resetSorting(),this._resetPager(),this.loadData(a)},loadData:function(a){a=a||(this.filtering?this.getFilter():{}),b.extend(a,this._loadStrategy.loadParams(),this._sortingParams());var c=this._callEventHandler(this.onDataLoading,{filter:a});return this._controllerCall("loadData",a,c.cancel,function(a){a&&(this._loadStrategy.finishLoad(a),this._callEventHandler(this.onDataLoaded,{data:a}))})},getFilter:function(){var a={};return this._eachField(function(b){b.filtering&&this._setItemFieldValue(a,b,b.filterValue())}),a},_sortingParams:function(){return this.sorting&&this._sortField?{sortField:this._sortField.name,sortOrder:this._sortOrder}:{}},getSorting:function(){var a=this._sortingParams();return{field:a.sortField,order:a.sortOrder}},clearFilter:function(){var a=this._createFilterRow();return this._filterRow.replaceWith(a),this._filterRow=a,this.search()},insertItem:function(a){var c=a||this._getValidatedInsertItem();if(!c)return b.Deferred().reject().promise();var d=this._callEventHandler(this.onItemInserting,{item:c});return this._controllerCall("insertItem",c,d.cancel,function(a){a=a||c,this._loadStrategy.finishInsert(a,this.insertRowLocation),this._callEventHandler(this.onItemInserted,{item:a})})},_getValidatedInsertItem:function(){var a=this._getInsertItem();return this._validateItem(a,this._insertRow)?a:null},_getInsertItem:function(){var a={};return this._eachField(function(b){b.inserting&&this._setItemFieldValue(a,b,b.insertValue())}),a},_validateItem:function(a,c){var d=[],e={item:a,itemIndex:this._rowIndex(c),row:c};if(this._eachField(function(f){if(f.validate&&(c!==this._insertRow||f.inserting)&&(c!==this._getEditRow()||f.editing)){var g=this._getItemFieldValue(a,f),h=this._validation.validate(b.extend({value:g,rules:f.validate},e));this._setCellValidity(c.children().eq(this._visibleFieldIndex(f)),h),h.length&&d.push.apply(d,b.map(h,function(a){return{field:f,message:a}}))}}),!d.length)return!0;var f=b.extend({errors:d},e);return this._callEventHandler(this.onItemInvalid,f),this.invalidNotify(f),!1},_setCellValidity:function(a,b){a.toggleClass(this.invalidClass,!!b.length).attr("title",b.join("\n"))},clearInsert:function(){var a=this._createInsertRow();this._insertRow.replaceWith(a),this._insertRow=a,this.refresh()},editItem:function(a){var b=this.rowByItem(a);b.length&&this._editRow(b)},rowByItem:function(a){return a.jquery||a.nodeType?b(a):this._content.find("tr").filter(function(){return b.data(this,g)===a})},_editRow:function(a){if(this.editing){var b=a.data(g);if(!this._callEventHandler(this.onItemEditing,{row:a,item:b,itemIndex:this._itemIndex(b)}).cancel){this._editingRow&&this.cancelEdit();var c=this._createEditRow(b);this._editingRow=a,a.hide(),c.insertBefore(a),a.data(h,c)}}},_createEditRow:function(a){if(b.isFunction(this.editRowRenderer))return b(this.renderTemplate(this.editRowRenderer,this,{item:a,itemIndex:this._itemIndex(a)}));var c=b("<tr>").addClass(this.editRowClass);return this._eachField(function(b){var d=this._getItemFieldValue(a,b);this._prepareCell("<td>",b,"editcss").append(this.renderTemplate(b.editTemplate||"",b,{value:d,item:a})).appendTo(c)}),c},updateItem:function(a,b){1===arguments.length&&(b=a);var c=a?this.rowByItem(a):this._editingRow;if(b=b||this._getValidatedEditedItem())return this._updateRow(c,b)},_getValidatedEditedItem:function(){var a=this._getEditedItem();return this._validateItem(a,this._getEditRow())?a:null},_updateRow:function(a,c){var d=a.data(g),e=this._itemIndex(d),f=b.extend(!0,{},d,c),h=this._callEventHandler(this.onItemUpdating,{row:a,item:f,itemIndex:e,previousItem:d});return this._controllerCall("updateItem",f,h.cancel,function(g){var h=b.extend(!0,{},d);f=g||b.extend(!0,d,c);var i=this._finishUpdate(a,f,e);this._callEventHandler(this.onItemUpdated,{row:i,item:f,itemIndex:e,previousItem:h})})},_rowIndex:function(a){return this._content.children().index(b(a))},_itemIndex:function(a){return b.inArray(a,this.data)},_finishUpdate:function(a,b,c){this.cancelEdit(),this.data[c]=b;var d=this._createRow(b,c);return a.replaceWith(d),d},_getEditedItem:function(){var a={};return this._eachField(function(b){b.editing&&this._setItemFieldValue(a,b,b.editValue())}),a},cancelEdit:function(){if(this._editingRow){var a=this._editingRow,b=a.data(g),c=this._itemIndex(b);this._callEventHandler(this.onItemEditCancelling,{row:a,item:b,itemIndex:c}),this._getEditRow().remove(),this._editingRow.show(),this._editingRow=null}},_getEditRow:function(){return this._editingRow&&this._editingRow.data(h)},deleteItem:function(b){var c=this.rowByItem(b);if(c.length&&(!this.confirmDeleting||a.confirm(j(this.deleteConfirm,this,c.data(g)))))return this._deleteRow(c)},_deleteRow:function(a){var b=a.data(g),c=this._itemIndex(b),d=this._callEventHandler(this.onItemDeleting,{row:a,item:b,itemIndex:c});return this._controllerCall("deleteItem",b,d.cancel,function(){this._loadStrategy.finishDelete(b,c),this._callEventHandler(this.onItemDeleted,{row:a,item:b,itemIndex:c})})}},b.fn.jsGrid=function(a){var e=b.makeArray(arguments),g=e.slice(1),h=this;return this.each(function(){var e,i=b(this),j=i.data(f);if(j)if("string"==typeof a){if(e=j[a].apply(j,g),e!==c&&e!==j)return h=e,!1}else j._detachWindowResizeCallback(),j._init(a),j.render();else new d(i,a)}),h};var m={},n=function(a){var c;b.isPlainObject(a)?c=d.prototype:(c=m[a].prototype,a=arguments[1]||{}),b.extend(c,a)},o={},p=function(a){var c=b.isPlainObject(a)?a:o[a];if(!c)throw Error("unknown locale "+a);q(jsGrid,c)},q=function(a,c){b.each(c,function(c,d){if(b.isPlainObject(d))return void q(a[c]||a[c[0].toUpperCase()+c.slice(1)],d);a.hasOwnProperty(c)?a[c]=d:a.prototype[c]=d})};a.jsGrid={Grid:d,fields:m,setDefaults:n,locales:o,locale:p,version:"1.5.3"}}(window,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={container:"body",message:"Loading...",shading:!0,zIndex:1e3,shaderClass:"jsgrid-load-shader",loadPanelClass:"jsgrid-load-panel",_init:function(a){b.extend(!0,this,a),this._initContainer(),this._initShader(),this._initLoadPanel()},_initContainer:function(){this._container=b(this.container)},_initShader:function(){this.shading&&(this._shader=b("<div>").addClass(this.shaderClass).hide().css({position:"absolute",top:0,right:0,bottom:0,left:0,zIndex:this.zIndex}).appendTo(this._container))},_initLoadPanel:function(){this._loadPanel=b("<div>").addClass(this.loadPanelClass).text(this.message).hide().css({position:"absolute",top:"50%",left:"50%",zIndex:this.zIndex}).appendTo(this._container)},show:function(){var a=this._loadPanel.show(),b=a.outerWidth(),c=a.outerHeight();a.css({marginTop:-c/2,marginLeft:-b/2}),this._shader.show()},hide:function(){this._loadPanel.hide(),this._shader.hide()}},a.LoadIndicator=d}(jsGrid,jQuery),function(a,b,c){function d(a){this._grid=a}function e(a){this._grid=a,this._itemsCount=0}d.prototype={firstDisplayIndex:function(){var a=this._grid;return a.option("paging")?(a.option("pageIndex")-1)*a.option("pageSize"):0},lastDisplayIndex:function(){var a=this._grid,b=a.option("data").length;return a.option("paging")?Math.min(a.option("pageIndex")*a.option("pageSize"),b):b},itemsCount:function(){return this._grid.option("data").length},openPage:function(a){this._grid.refresh()},loadParams:function(){return{}},sort:function(){return this._grid._sortData(),this._grid.refresh(),b.Deferred().resolve().promise()},reset:function(){return this._grid.refresh(),b.Deferred().resolve().promise()},finishLoad:function(a){this._grid.option("data",a)},finishInsert:function(a,b){var c=this._grid;switch(b){case"top":c.option("data").unshift(a);break;case"bottom":default:c.option("data").push(a)}c.refresh()},finishDelete:function(a,b){var c=this._grid;c.option("data").splice(b,1),c.reset()}},e.prototype={firstDisplayIndex:function(){return 0},lastDisplayIndex:function(){return this._grid.option("data").length},itemsCount:function(){return this._itemsCount},openPage:function(a){this._grid.loadData()},loadParams:function(){var a=this._grid;return{pageIndex:a.option("pageIndex"),pageSize:a.option("pageSize")}},reset:function(){return this._grid.loadData()},sort:function(){return this._grid.loadData()},finishLoad:function(a){this._itemsCount=a.itemsCount,this._grid.option("data",a.data)},finishInsert:function(a){this._grid.search()},finishDelete:function(a,b){this._grid.search()}},a.loadStrategies={DirectLoadingStrategy:d,PageLoadingStrategy:e}}(jsGrid,jQuery),function(a,b,c){var d=function(a){return void 0!==a&&null!==a},e={string:function(a,b){return d(a)||d(b)?d(a)?d(b)?(""+a).localeCompare(""+b):1:-1:0},number:function(a,b){return a-b},date:function(a,b){return a-b},numberAsString:function(a,b){return parseFloat(a)-parseFloat(b)}};a.sortStrategies=e}(jsGrid,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={_init:function(a){b.extend(!0,this,a)},validate:function(a){var c=[];return b.each(this._normalizeRules(a.rules),function(d,e){if(!e.validator(a.value,a.item,e.param)){var f=b.isFunction(e.message)?e.message(a.value,a.item):e.message;c.push(f)}}),c},_normalizeRules:function(a){return b.isArray(a)||(a=[a]),b.map(a,b.proxy(function(a){return this._normalizeRule(a)},this))},_normalizeRule:function(a){if("string"==typeof a&&(a={validator:a}),b.isFunction(a)&&(a={validator:a}),!b.isPlainObject(a))throw Error("wrong validation config specified");return a=b.extend({},a),b.isFunction(a.validator)?a:this._applyNamedValidator(a,a.validator)},_applyNamedValidator:function(a,c){delete a.validator;var d=e[c];if(!d)throw Error('unknown validator "'+c+'"');return b.isFunction(d)&&(d={validator:d}),b.extend({},d,a)}},a.Validation=d;var e={required:{message:"Field is required",validator:function(a){return a!==c&&null!==a&&""!==a}},rangeLength:{message:"Field value length is out of the defined range",validator:function(a,b,c){return a.length>=c[0]&&a.length<=c[1]}},minLength:{message:"Field value is too short",validator:function(a,b,c){return a.length>=c}},maxLength:{message:"Field value is too long",validator:function(a,b,c){return a.length<=c}},pattern:{message:"Field value is not matching the defined pattern",validator:function(a,b,c){return"string"==typeof c&&(c=new RegExp("^(?:"+c+")$")),c.test(a)}},range:{message:"Field value is out of the defined range",validator:function(a,b,c){return a>=c[0]&&a<=c[1]}},min:{message:"Field value is too small",validator:function(a,b,c){return a>=c}},max:{message:"Field value is too large",validator:function(a,b,c){return a<=c}}};a.validators=e}(jsGrid,jQuery),function(a,b,c){function d(a){b.extend(!0,this,a),this.sortingFunc=this._getSortingFunc()}d.prototype={name:"",title:null,css:"",align:"",width:100,visible:!0,filtering:!0,inserting:!0,editing:!0,sorting:!0,sorter:"string",headerTemplate:function(){return this.title===c||null===this.title?this.name:this.title},itemTemplate:function(a,b){return a},filterTemplate:function(){return""},insertTemplate:function(){return""},editTemplate:function(a,b){return this._value=a,this.itemTemplate(a,b)},filterValue:function(){return""},insertValue:function(){return""},editValue:function(){return this._value},_getSortingFunc:function(){var c=this.sorter;if(b.isFunction(c))return c;if("string"==typeof c)return a.sortStrategies[c];throw Error('wrong sorter for the field "'+this.name+'"!')}},a.Field=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({autosearch:!0,readOnly:!1,filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createTextBox();return this.autosearch&&b.on("keypress",function(b){13===b.which&&(a.search(),b.preventDefault())}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createTextBox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextBox();return b.val(a),b},filterValue:function(){return this.filterControl.val()},insertValue:function(){return this.insertControl.val()},editValue:function(){return this.editControl.val()},_createTextBox:function(){return b("<input>").attr("type","text").prop("readonly",!!this.readOnly)}}),a.fields.text=a.TextField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({sorter:"number",align:"right",readOnly:!1,filterValue:function(){return this.filterControl.val()?parseInt(this.filterControl.val()||0,10):c},insertValue:function(){return this.insertControl.val()?parseInt(this.insertControl.val()||0,10):c},editValue:function(){return this.editControl.val()?parseInt(this.editControl.val()||0,10):c},_createTextBox:function(){return b("<input>").attr("type","number").prop("readonly",!!this.readOnly)}}),a.fields.number=a.NumberField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({insertTemplate:function(){return this.inserting?this.insertControl=this._createTextArea():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextArea();return b.val(a),b},_createTextArea:function(){return b("<textarea>").prop("readonly",!!this.readOnly)}}),a.fields.textarea=a.TextAreaField=d}(jsGrid,jQuery),function(a,b,c){function d(a){if(this.items=[],this.selectedIndex=-1,this.valueField="",this.textField="",a.valueField&&a.items.length){var b=a.items[0][a.valueField];this.valueType=typeof b===f?f:g}this.sorter=this.valueType,e.call(this,a)}var e=a.NumberField,f="number",g="string";d.prototype=new e({align:"center",valueType:f,itemTemplate:function(a){var d,e=this.items,f=this.valueField,g=this.textField;d=f?b.grep(e,function(b,c){return b[f]===a})[0]||{}:e[a];var h=g?d[g]:d;return h===c||null===h?"":h},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createSelect();return this.autosearch&&b.on("change",function(b){a.search()}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createSelect():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createSelect();return a!==c&&b.val(a),b},filterValue:function(){var a=this.filterControl.val();return this.valueType===f?parseInt(a||0,10):a},insertValue:function(){var a=this.insertControl.val();return this.valueType===f?parseInt(a||0,10):a},editValue:function(){var a=this.editControl.val();return this.valueType===f?parseInt(a||0,10):a},_createSelect:function(){var a=b("<select>"),c=this.valueField,d=this.textField,e=this.selectedIndex;return b.each(this.items,function(e,f){var g=c?f[c]:e,h=d?f[d]:f;b("<option>").attr("value",g).text(h).appendTo(a)}),a.prop("disabled",!!this.readOnly),a.prop("selectedIndex",e),a}}),a.fields.select=a.SelectField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({sorter:"number",align:"center",autosearch:!0,itemTemplate:function(a){return this._createCheckbox().prop({checked:a,disabled:!0})},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,c=this.filterControl=this._createCheckbox();return c.prop({readOnly:!0,indeterminate:!0}),c.on("click",function(){var a=b(this);a.prop("readOnly")?a.prop({checked:!1,readOnly:!1}):a.prop("checked")||a.prop({readOnly:!0,indeterminate:!0})}),this.autosearch&&c.on("click",function(){a.search()}),c},insertTemplate:function(){return this.inserting?this.insertControl=this._createCheckbox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createCheckbox();return b.prop("checked",a),b},filterValue:function(){return this.filterControl.get(0).indeterminate?c:this.filterControl.is(":checked")},insertValue:function(){return this.insertControl.is(":checked")},editValue:function(){return this.editControl.is(":checked")},_createCheckbox:function(){return b("<input>").attr("type","checkbox")}}),a.fields.checkbox=a.CheckboxField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a),this._configInitialized=!1}var e=a.Field;d.prototype=new e({css:"jsgrid-control-field",align:"center",width:50,filtering:!1,inserting:!1,editing:!1,sorting:!1,buttonClass:"jsgrid-button",modeButtonClass:"jsgrid-mode-button",modeOnButtonClass:"jsgrid-mode-on-button",searchModeButtonClass:"jsgrid-search-mode-button",insertModeButtonClass:"jsgrid-insert-mode-button",editButtonClass:"jsgrid-edit-button",deleteButtonClass:"jsgrid-delete-button",searchButtonClass:"jsgrid-search-button",clearFilterButtonClass:"jsgrid-clear-filter-button",insertButtonClass:"jsgrid-insert-button",updateButtonClass:"jsgrid-update-button",cancelEditButtonClass:"jsgrid-cancel-edit-button",searchModeButtonTooltip:"Switch to searching",insertModeButtonTooltip:"Switch to inserting",editButtonTooltip:"Edit",deleteButtonTooltip:"Delete",searchButtonTooltip:"Search",clearFilterButtonTooltip:"Clear filter",insertButtonTooltip:"Insert",updateButtonTooltip:"Update",cancelEditButtonTooltip:"Cancel edit",editButton:!0,deleteButton:!0,clearFilterButton:!0,modeSwitchButton:!0,_initConfig:function(){this._hasFiltering=this._grid.filtering,this._hasInserting=this._grid.inserting,this._hasInserting&&this.modeSwitchButton&&(this._grid.inserting=!1),this._configInitialized=!0},headerTemplate:function(){this._configInitialized||this._initConfig();var a=this._hasFiltering,b=this._hasInserting;return this.modeSwitchButton&&(a||b)?a&&!b?this._createFilterSwitchButton():b&&!a?this._createInsertSwitchButton():this._createModeSwitchButton():""},itemTemplate:function(a,c){var d=b([]);return this.editButton&&(d=d.add(this._createEditButton(c))),this.deleteButton&&(d=d.add(this._createDeleteButton(c))),d},filterTemplate:function(){var a=this._createSearchButton();return this.clearFilterButton?a.add(this._createClearFilterButton()):a},insertTemplate:function(){return this._createInsertButton()},editTemplate:function(){return this._createUpdateButton().add(this._createCancelEditButton())},_createFilterSwitchButton:function(){return this._createOnOffSwitchButton("filtering",this.searchModeButtonClass,!0)},_createInsertSwitchButton:function(){return this._createOnOffSwitchButton("inserting",this.insertModeButtonClass,!1)},_createOnOffSwitchButton:function(a,c,d){var e=d,f=b.proxy(function(){g.toggleClass(this.modeOnButtonClass,e)},this),g=this._createGridButton(this.modeButtonClass+" "+c,"",function(b){e=!e,b.option(a,e),f()});return f(),g},_createModeSwitchButton:function(){var a=!1,c=b.proxy(function(){d.attr("title",a?this.searchModeButtonTooltip:this.insertModeButtonTooltip).toggleClass(this.insertModeButtonClass,!a).toggleClass(this.searchModeButtonClass,a)},this),d=this._createGridButton(this.modeButtonClass,"",function(b){a=!a,b.option("inserting",a),b.option("filtering",!a),c()});return c(),d},_createEditButton:function(a){return this._createGridButton(this.editButtonClass,this.editButtonTooltip,function(b,c){b.editItem(a),c.stopPropagation()})},_createDeleteButton:function(a){return this._createGridButton(this.deleteButtonClass,this.deleteButtonTooltip,function(b,c){b.deleteItem(a),c.stopPropagation()})},_createSearchButton:function(){return this._createGridButton(this.searchButtonClass,this.searchButtonTooltip,function(a){a.search()})},_createClearFilterButton:function(){return this._createGridButton(this.clearFilterButtonClass,this.clearFilterButtonTooltip,function(a){a.clearFilter()})},_createInsertButton:function(){return this._createGridButton(this.insertButtonClass,this.insertButtonTooltip,function(a){a.insertItem().done(function(){a.clearInsert()})})},_createUpdateButton:function(){return this._createGridButton(this.updateButtonClass,this.updateButtonTooltip,function(a,b){a.updateItem(),b.stopPropagation()})},_createCancelEditButton:function(){return this._createGridButton(this.cancelEditButtonClass,this.cancelEditButtonTooltip,function(a,b){a.cancelEdit(),b.stopPropagation()})},_createGridButton:function(a,c,d){var e=this._grid;return b("<input>").addClass(this.buttonClass).addClass(a).attr({type:"button",title:c}).on("click",function(a){d(e,a)})},editValue:function(){return""}}),a.fields.control=a.ControlField=d}(jsGrid,jQuery); <MSG> Brought dist/ back to 1.5.3 <DFF> @@ -1,7 +1,8 @@ /* * jsGrid v1.5.3 (http://js-grid.com) - * (c) 2017 Artem Tabalin + * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ -!function(a,b,c){function d(a,c){var d=b(a);d.data(f,this),this._container=d,this.data=[],this.fields=[],this._editingRow=null,this._sortField=null,this._sortOrder=i,this._firstDisplayingPage=1,this._init(c),this.render()}var e="JSGrid",f=e,g="JSGridItem",h="JSGridEditRow",i="asc",j=function(a,c){return b.isFunction(a)?a.apply(c,b.makeArray(arguments).slice(2)):a},k=function(a){var c=b.Deferred();return a&&a.then?a.then(function(){c.resolve.apply(c,arguments)},function(){c.reject.apply(c,arguments)}):c.resolve(a),c.promise()},l={loadData:b.noop,insertItem:b.noop,updateItem:b.noop,deleteItem:b.noop};d.prototype={width:"auto",height:"auto",updateOnResize:!0,rowClass:b.noop,rowRenderer:null,rowClick:function(a){this.editing&&this.editItem(b(a.event.target).closest("tr"))},rowDoubleClick:b.noop,noDataContent:"Not found",noDataRowClass:"jsgrid-nodata-row",heading:!0,headerRowRenderer:null,headerRowClass:"jsgrid-header-row",headerCellClass:"jsgrid-header-cell",filtering:!1,filterRowRenderer:null,filterRowClass:"jsgrid-filter-row",inserting:!1,insertRowLocation:"bottom",insertRowRenderer:null,insertRowClass:"jsgrid-insert-row",editing:!1,editRowRenderer:null,editRowClass:"jsgrid-edit-row",confirmDeleting:!0,deleteConfirm:"Are you sure?",selecting:!0,selectedRowClass:"jsgrid-selected-row",oddRowClass:"jsgrid-row",evenRowClass:"jsgrid-alt-row",cellClass:"jsgrid-cell",sorting:!1,sortableClass:"jsgrid-header-sortable",sortAscClass:"jsgrid-header-sort jsgrid-header-sort-asc",sortDescClass:"jsgrid-header-sort jsgrid-header-sort-desc",paging:!1,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",pagerNavButtonInactiveClass:"jsgrid-pager-nav-inactive-button",pageClass:"jsgrid-pager-page",currentPageClass:"jsgrid-pager-current-page",customLoading:!1,pageLoading:!1,autoload:!1,controller:l,loadIndication:!0,loadIndicationDelay:500,loadMessage:"Please, wait...",loadShading:!0,invalidMessage:"Invalid data entered!",invalidNotify:function(c){var d=b.map(c.errors,function(a){return a.message||null});a.alert([this.invalidMessage].concat(d).join("\n"))},onInit:b.noop,onRefreshing:b.noop,onRefreshed:b.noop,onPageChanged:b.noop,onItemDeleting:b.noop,onItemDeleted:b.noop,onItemInserting:b.noop,onItemInserted:b.noop,onItemEditing:b.noop,onItemEditCancelling:b.noop,onItemUpdating:b.noop,onItemUpdated:b.noop,onItemInvalid:b.noop,onDataLoading:b.noop,onDataLoaded:b.noop,onOptionChanging:b.noop,onOptionChanged:b.noop,onError:b.noop,invalidClass:"jsgrid-invalid",containerClass:"jsgrid",tableClass:"jsgrid-table",gridHeaderClass:"jsgrid-grid-header",gridBodyClass:"jsgrid-grid-body",_init:function(a){b.extend(this,a),this._initLoadStrategy(),this._initController(),this._initFields(),this._attachWindowLoadResize(),this._attachWindowResizeCallback(),this._callEventHandler(this.onInit)},loadStrategy:function(){return this.pageLoading?new jsGrid.loadStrategies.PageLoadingStrategy(this):new jsGrid.loadStrategies.DirectLoadingStrategy(this)},_initLoadStrategy:function(){this._loadStrategy=j(this.loadStrategy,this)},_initController:function(){this._controller=b.extend({},l,j(this.controller,this))},renderTemplate:function(a,b,d){args=[];for(var e in d)args.push(d[e]);return args.unshift(a,b),a=j.apply(null,args),a===c||null===a?"":a},loadIndicator:function(a){return new jsGrid.LoadIndicator(a)},validation:function(a){return jsGrid.Validation&&new jsGrid.Validation(a)},_initFields:function(){var a=this;a.fields=b.map(a.fields,function(c){return b.isPlainObject(c)&&(c=new(c.type&&jsGrid.fields[c.type]||jsGrid.Field)(c)),c._grid=a,c})},_attachWindowLoadResize:function(){b(a).on("load",b.proxy(this._refreshSize,this))},_attachWindowResizeCallback:function(){this.updateOnResize&&b(a).on("resize",b.proxy(this._refreshSize,this))},_detachWindowResizeCallback:function(){b(a).off("resize",this._refreshSize)},option:function(a,b){var c,d;if(1===arguments.length)return this[a];c={option:a,oldValue:this[a],newValue:b},this._callEventHandler(this.onOptionChanging,c),this._handleOptionChange(c.option,c.newValue),d={option:c.option,value:c.newValue},this._callEventHandler(this.onOptionChanged,d)},fieldOption:function(a,b,c){if(a=this._normalizeField(a),2===arguments.length)return a[b];a[b]=c,this._renderGrid()},_handleOptionChange:function(a,b){switch(this[a]=b,a){case"width":case"height":this._refreshSize();break;case"rowClass":case"rowRenderer":case"rowClick":case"rowDoubleClick":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":case"pagerRenderer":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"loadStrategy":case"pageLoading":this._initLoadStrategy(),this.search();break;case"pageIndex":this.openPage(b);break;case"pageSize":this.refresh(),this.search();break;case"editRowRenderer":case"editRowClass":this.cancelEdit();break;case"updateOnResize":this._detachWindowResizeCallback(),this._attachWindowResizeCallback();break;case"invalidNotify":case"invalidMessage":break;default:this.render()}},destroy:function(){this._detachWindowResizeCallback(),this._clear(),this._container.removeData(f)},render:function(){return this._renderGrid(),this.autoload?this.loadData():b.Deferred().resolve().promise()},_renderGrid: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._validation=this._createValidation(),this.refresh()},_createLoadIndicator:function(){return j(this.loadIndicator,this,{message:this.loadMessage,shading:this.loadShading,container:this._container})},_createValidation:function(){return j(this.validation,this)},_clear:function(){this.cancelEdit(),clearTimeout(this._loadingTimer),this._pagerContainer&&this._pagerContainer.empty(),this._container.empty().css({position:"",width:"",height:""})},_createHeader:function(){var a=this._headerRow=this._createHeaderRow(),c=this._filterRow=this._createFilterRow(),d=this._insertRow=this._createInsertRow(),e=this._headerGrid=b("<table>").addClass(this.tableClass).append(a).append(c).append(d);return this._header=b("<div>").addClass(this.gridHeaderClass).addClass(this._scrollBarWidth()?"jsgrid-header-scrollbar":"").append(e)},_createBody:function(){var a=this._content=b("<tbody>"),c=this._bodyGrid=b("<table>").addClass(this.tableClass).append(a);return this._body=b("<div>").addClass(this.gridBodyClass).append(c).on("scroll",b.proxy(function(a){this._header.scrollLeft(a.target.scrollLeft)},this))},_createPagerContainer:function(){return b(this.pagerContainer||b("<div>").appendTo(this._container)).addClass(this.pagerContainerClass)},_eachField:function(a){var c=this;b.each(this.fields,function(b,d){d.visible&&a.call(c,d,b)})},_createHeaderRow:function(){if(b.isFunction(this.headerRowRenderer))return b(this.renderTemplate(this.headerRowRenderer,this));var a=b("<tr>").addClass(this.headerRowClass);return this._eachField(function(c,d){var e=this._prepareCell("<th>",c,"headercss",this.headerCellClass).append(this.renderTemplate(c.headerTemplate,c)).appendTo(a);this.sorting&&c.sorting&&e.addClass(this.sortableClass).on("click",b.proxy(function(){this.sort(d)},this))}),a},_prepareCell:function(a,c,d,e){return b(a).css("width",c.width).addClass(e||this.cellClass).addClass(d&&c[d]||c.css).addClass(c.align?"jsgrid-align-"+c.align:"")},_createFilterRow:function(){if(b.isFunction(this.filterRowRenderer))return b(this.renderTemplate(this.filterRowRenderer,this));var a=b("<tr>").addClass(this.filterRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"filtercss").append(this.renderTemplate(b.filterTemplate,b)).appendTo(a)}),a},_createInsertRow:function(){if(b.isFunction(this.insertRowRenderer))return b(this.renderTemplate(this.insertRowRenderer,this));var a=b("<tr>").addClass(this.insertRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"insertcss").append(this.renderTemplate(b.insertTemplate,b)).appendTo(a)}),a},_callEventHandler:function(a,c){return a.call(this,b.extend(c,{grid:this})),c},reset:function(){return this._resetSorting(),this._resetPager(),this._loadStrategy.reset()},_resetPager:function(){this._firstDisplayingPage=1,this._setPage(1)},_resetSorting:function(){this._sortField=null,this._sortOrder=i,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 a=this._content;if(a.empty(),!this.data.length)return a.append(this._createNoDataRow()),this;for(var b=this._loadStrategy.firstDisplayIndex(),c=this._loadStrategy.lastDisplayIndex(),d=b;d<c;d++){var e=this.data[d];a.append(this._createRow(e,d))}},_createNoDataRow:function(){var a=0;return this._eachField(function(){a++}),b("<tr>").addClass(this.noDataRowClass).append(b("<td>").addClass(this.cellClass).attr("colspan",a).append(this.renderTemplate(this.noDataContent,this)))},_createRow:function(a,c){var d;return b.isFunction(this.rowRenderer)?d=this.renderTemplate(this.rowRenderer,this,{item:a,itemIndex:c}):(d=b("<tr>"),this._renderCells(d,a)),d.addClass(this._getRowClasses(a,c)).data(g,a).on("click",b.proxy(function(b){this.rowClick({item:a,itemIndex:c,event:b})},this)).on("dblclick",b.proxy(function(b){this.rowDoubleClick({item:a,itemIndex:c,event:b})},this)),this.selecting&&this._attachRowHover(d),d},_getRowClasses:function(a,b){var c=[];return c.push((b+1)%2?this.oddRowClass:this.evenRowClass),c.push(j(this.rowClass,this,a,b)),c.join(" ")},_attachRowHover:function(a){var c=this.selectedRowClass;a.hover(function(){b(this).addClass(c)},function(){b(this).removeClass(c)})},_renderCells:function(a,b){return this._eachField(function(c){a.append(this._createCell(b,c))}),this},_createCell:function(a,c){var d,e=this._getItemFieldValue(a,c),f={value:e,item:a};return d=b.isFunction(c.cellRenderer)?this.renderTemplate(c.cellRenderer,c,f):b("<td>").append(this.renderTemplate(c.itemTemplate||e,c,f)),this._prepareCell(d,c)},_getItemFieldValue:function(a,b){for(var c=b.name.split("."),d=a[c.shift()];d&&c.length;)d=d[c.shift()];return d},_setItemFieldValue:function(a,b,c){for(var d=b.name.split("."),e=a,f=d[0];e&&d.length;)a=e,f=d.shift(),e=a[f];if(!e)for(;d.length;)a=a[f]={},f=d.shift();a[f]=c},sort:function(a,c){return b.isPlainObject(a)&&(c=a.order,a=a.field),this._clearSortingCss(),this._setSortingParams(a,c),this._setSortingCss(),this._loadStrategy.sort()},_clearSortingCss:function(){this._headerRow.find("th").removeClass(this.sortAscClass).removeClass(this.sortDescClass)},_setSortingParams:function(a,b){a=this._normalizeField(a),b=b||(this._sortField===a?this._reversedSortOrder(this._sortOrder):i),this._sortField=a,this._sortOrder=b},_normalizeField:function(a){return b.isNumeric(a)?this.fields[a]:"string"==typeof a?b.grep(this.fields,function(b){return b.name===a})[0]:a},_reversedSortOrder:function(a){return a===i?"desc":i},_setSortingCss:function(){var a=this._visibleFieldIndex(this._sortField);this._headerRow.find("th").eq(a).addClass(this._sortOrder===i?this.sortAscClass:this.sortDescClass)},_visibleFieldIndex:function(a){return b.inArray(a,b.grep(this.fields,function(a){return a.visible}))},_sortData:function(){var a=this._sortFactor(),b=this._sortField;b&&this.data.sort(function(c,d){return a*b.sortingFunc(c[b.name],d[b.name])})},_sortFactor:function(){return this._sortOrder===i?1:-1},_itemsCount:function(){return this._loadStrategy.itemsCount()},_pagesCount:function(){var a=this._itemsCount(),b=this.pageSize;return Math.floor(a/b)+(a%b?1:0)},_refreshPager:function(){var a=this._pagerContainer;a.empty(),this.paging&&a.append(this._createPager());var b=this.paging&&this._pagesCount()>1;a.toggle(b)},_createPager:function(){var a;return a=b.isFunction(this.pagerRenderer)?b(this.pagerRenderer({pageIndex:this.pageIndex,pageCount:this._pagesCount()})):b("<div>").append(this._createPagerByFormat()),a.addClass(this.pagerClass),a},_createPagerByFormat:function(){var a=this.pageIndex,c=this._pagesCount(),d=this._itemsCount(),e=this.pagerFormat.split(" ");return b.map(e,b.proxy(function(e){var f=e;return"{pages}"===e?f=this._createPages():"{first}"===e?f=this._createPagerNavButton(this.pageFirstText,1,a>1):"{prev}"===e?f=this._createPagerNavButton(this.pagePrevText,a-1,a>1):"{next}"===e?f=this._createPagerNavButton(this.pageNextText,a+1,a<c):"{last}"===e?f=this._createPagerNavButton(this.pageLastText,c,a<c):"{pageIndex}"===e?f=a:"{pageCount}"===e?f=c:"{itemCount}"===e&&(f=d),b.isArray(f)?f.concat([" "]):[f," "]},this))},_createPages:function(){var a=this._pagesCount(),b=this.pageButtonCount,c=this._firstDisplayingPage,d=[];c>1&&d.push(this._createPagerPageNavButton(this.pageNavigatorPrevText,this.showPrevPages));for(var e=0,f=c;e<b&&f<=a;e++,f++)d.push(f===this.pageIndex?this._createPagerCurrentPage():this._createPagerPage(f));return c+b-1<a&&d.push(this._createPagerPageNavButton(this.pageNavigatorNextText,this.showNextPages)),d},_createPagerNavButton:function(a,c,d){return this._createPagerButton(a,this.pagerNavButtonClass+(d?"":" "+this.pagerNavButtonInactiveClass),d?function(){this.openPage(c)}:b.noop)},_createPagerPageNavButton:function(a,b){return this._createPagerButton(a,this.pagerNavButtonClass,b)},_createPagerPage:function(a){return this._createPagerButton(a,this.pageClass,function(){this.openPage(a)})},_createPagerButton:function(a,c,d){var e=b("<a>").attr("href","javascript:void(0);").html(a).on("click",b.proxy(d,this));return b("<span>").addClass(c).append(e)},_createPagerCurrentPage:function(){return b("<span>").addClass(this.pageClass).addClass(this.currentPageClass).text(this.pageIndex)},_refreshSize:function(){this._refreshHeight(),this._refreshWidth()},_refreshWidth:function(){var a="auto"===this.width?this._getAutoWidth():this.width;this._container.width(a)},_getAutoWidth:function(){var a=this._headerGrid,b=this._header;a.width("auto");var c=a.outerWidth(),d=b.outerWidth()-b.innerWidth();return a.width(""),c+d},_scrollBarWidth:function(){var a;return function(){if(a===c){var d=b("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"),e=b("<div style='height:100px;'></div>");d.append(e).appendTo("body");var f=e.innerWidth();d.css("overflow-y","auto");var g=e.innerWidth();d.remove(),a=f-g}return a}}(),_refreshHeight:function(){var a,b=this._container,c=this._pagerContainer,d=this.height;b.height(d),"auto"!==d&&(d=b.height(),a=this._header.outerHeight(!0),c.parents(b).length&&(a+=c.outerHeight(!0)),this._body.outerHeight(d-a))},showPrevPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount;this._firstDisplayingPage=a>b?a-b:1,this._refreshPager()},showNextPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount,c=this._pagesCount();this._firstDisplayingPage=a+2*b>c?c-b+1:a+b,this._refreshPager()},openPage:function(a){a<1||a>this._pagesCount()||(this._setPage(a),this._loadStrategy.openPage(a))},_setPage:function(a){var b=this._firstDisplayingPage,c=this.pageButtonCount;this.pageIndex=a,a<b&&(this._firstDisplayingPage=a),a>b+c-1&&(this._firstDisplayingPage=a-c+1),this._callEventHandler(this.onPageChanged,{pageIndex:a})},_controllerCall:function(a,c,d,e){if(d)return b.Deferred().reject().promise();this._showLoading();var f=this._controller;if(!f||!f[a])throw Error("controller has no method '"+a+"'");return k(f[a](c)).done(b.proxy(e,this)).fail(b.proxy(this._errorHandler,this)).always(b.proxy(this._hideLoading,this))},_errorHandler:function(){this._callEventHandler(this.onError,{args:b.makeArray(arguments)})},_showLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadingTimer=setTimeout(b.proxy(function(){this._loadIndicator.show()},this),this.loadIndicationDelay))},_hideLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadIndicator.hide())},search:function(a){return this._resetSorting(),this._resetPager(),this.loadData(a)},loadData:function(a){a=a||(this.filtering?this.getFilter():{}),b.extend(a,this._loadStrategy.loadParams(),this._sortingParams());var c=this._callEventHandler(this.onDataLoading,{filter:a});return this._controllerCall("loadData",a,c.cancel,function(a){a&&(this._loadStrategy.finishLoad(a),this._callEventHandler(this.onDataLoaded,{data:a}))})},getFilter:function(){var a={};return this._eachField(function(b){b.filtering&&this._setItemFieldValue(a,b,b.filterValue())}),a},_sortingParams:function(){return this.sorting&&this._sortField?{sortField:this._sortField.name,sortOrder:this._sortOrder}:{}},getSorting:function(){var a=this._sortingParams();return{field:a.sortField,order:a.sortOrder}},clearFilter:function(){var a=this._createFilterRow();return this._filterRow.replaceWith(a),this._filterRow=a,this.search()},insertItem:function(a){var c=a||this._getValidatedInsertItem();if(!c)return b.Deferred().reject().promise();var d=this._callEventHandler(this.onItemInserting,{item:c});return this._controllerCall("insertItem",c,d.cancel,function(a){a=a||c,this._loadStrategy.finishInsert(a,this.insertRowLocation),this._callEventHandler(this.onItemInserted,{item:a})})},_getValidatedInsertItem:function(){var a=this._getInsertItem();return this._validateItem(a,this._insertRow)?a:null},_getInsertItem:function(){var a={};return this._eachField(function(b){b.inserting&&this._setItemFieldValue(a,b,b.insertValue())}),a},_validateItem:function(a,c){var d=[],e={item:a,itemIndex:this._rowIndex(c),row:c};if(this._eachField(function(f){if(f.validate&&(c!==this._insertRow||f.inserting)&&(c!==this._getEditRow()||f.editing)){var g=this._getItemFieldValue(a,f),h=this._validation.validate(b.extend({value:g,rules:f.validate},e));this._setCellValidity(c.children().eq(this._visibleFieldIndex(f)),h),h.length&&d.push.apply(d,b.map(h,function(a){return{field:f,message:a}}))}}),!d.length)return!0;var f=b.extend({errors:d},e);return this._callEventHandler(this.onItemInvalid,f),this.invalidNotify(f),!1},_setCellValidity:function(a,b){a.toggleClass(this.invalidClass,!!b.length).attr("title",b.join("\n"))},clearInsert:function(){var a=this._createInsertRow();this._insertRow.replaceWith(a),this._insertRow=a,this.refresh()},editItem:function(a){var b=this.rowByItem(a);b.length&&this._editRow(b)},rowByItem:function(a){return a.jquery||a.nodeType?b(a):this._content.find("tr").filter(function(){return b.data(this,g)===a})},_editRow:function(a){if(this.editing){var b=a.data(g);if(!this._callEventHandler(this.onItemEditing,{row:a,item:b,itemIndex:this._itemIndex(b)}).cancel){this._editingRow&&this.cancelEdit();var c=this._createEditRow(b);this._editingRow=a,a.hide(),c.insertBefore(a),a.data(h,c)}}},_createEditRow:function(a){if(b.isFunction(this.editRowRenderer))return b(this.renderTemplate(this.editRowRenderer,this,{item:a,itemIndex:this._itemIndex(a)}));var c=b("<tr>").addClass(this.editRowClass);return this._eachField(function(b){var d=this._getItemFieldValue(a,b);this._prepareCell("<td>",b,"editcss").append(this.renderTemplate(b.editTemplate||"",b,{value:d,item:a})).appendTo(c)}),c},updateItem:function(a,b){1===arguments.length&&(b=a);var c=a?this.rowByItem(a):this._editingRow;if(b=b||this._getValidatedEditedItem())return this._updateRow(c,b)},_getValidatedEditedItem:function(){var a=this._getEditedItem();return this._validateItem(a,this._getEditRow())?a:null},_updateRow:function(a,c){var d=a.data(g),e=this._itemIndex(d),f=b.extend(!0,{},d,c),h=this._callEventHandler(this.onItemUpdating,{row:a,item:f,itemIndex:e,previousItem:d});return this._controllerCall("updateItem",f,h.cancel,function(g){var h=b.extend(!0,{},d);f=g||b.extend(!0,d,c);var i=this._finishUpdate(a,f,e);this._callEventHandler(this.onItemUpdated,{row:i,item:f,itemIndex:e,previousItem:h})})},_rowIndex:function(a){return this._content.children().index(b(a))},_itemIndex:function(a){return b.inArray(a,this.data)},_finishUpdate:function(a,b,c){this.cancelEdit(),this.data[c]=b;var d=this._createRow(b,c);return a.replaceWith(d),d},_getEditedItem:function(){var a={};return this._eachField(function(b){b.editing&&this._setItemFieldValue(a,b,b.editValue())}),a},cancelEdit:function(){if(this._editingRow){var a=this._editingRow,b=a.data(g),c=this._itemIndex(b);this._callEventHandler(this.onItemEditCancelling,{row:a,item:b,itemIndex:c}),this._getEditRow().remove(),this._editingRow.show(),this._editingRow=null}},_getEditRow:function(){return this._editingRow&&this._editingRow.data(h)},deleteItem:function(b){var c=this.rowByItem(b);if(c.length&&(!this.confirmDeleting||a.confirm(j(this.deleteConfirm,this,c.data(g)))))return this._deleteRow(c)},_deleteRow:function(a){var b=a.data(g),c=this._itemIndex(b),d=this._callEventHandler(this.onItemDeleting,{row:a,item:b,itemIndex:c});return this._controllerCall("deleteItem",b,d.cancel,function(){this._loadStrategy.finishDelete(b,c),this._callEventHandler(this.onItemDeleted,{row:a,item:b,itemIndex:c})})}},b.fn.jsGrid=function(a){var e=b.makeArray(arguments),g=e.slice(1),h=this;return this.each(function(){var e,i=b(this),j=i.data(f);if(j)if("string"==typeof a){if(e=j[a].apply(j,g),e!==c&&e!==j)return h=e,!1}else j._detachWindowResizeCallback(),j._init(a),j.render();else new d(i,a)}),h};var m={},n=function(a){var c;b.isPlainObject(a)?c=d.prototype:(c=m[a].prototype,a=arguments[1]||{}),b.extend(c,a)},o={},p=function(a){var c=b.isPlainObject(a)?a:o[a];if(!c)throw Error("unknown locale "+a);q(jsGrid,c)},q=function(a,c){b.each(c,function(c,d){if(b.isPlainObject(d))return void q(a[c]||a[c[0].toUpperCase()+c.slice(1)],d);a.hasOwnProperty(c)?a[c]=d:a.prototype[c]=d})};a.jsGrid={Grid:d,fields:m,setDefaults:n,locales:o,locale:p,version:"1.5.3"}}(window,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={container:"body",message:"Loading...",shading:!0,zIndex:1e3,shaderClass:"jsgrid-load-shader",loadPanelClass:"jsgrid-load-panel",_init:function(a){b.extend(!0,this,a),this._initContainer(),this._initShader(),this._initLoadPanel()},_initContainer:function(){this._container=b(this.container)},_initShader:function(){this.shading&&(this._shader=b("<div>").addClass(this.shaderClass).hide().css({position:"absolute",top:0,right:0,bottom:0,left:0,zIndex:this.zIndex}).appendTo(this._container))},_initLoadPanel:function(){this._loadPanel=b("<div>").addClass(this.loadPanelClass).text(this.message).hide().css({position:"absolute",top:"50%",left:"50%",zIndex:this.zIndex}).appendTo(this._container)},show:function(){var a=this._loadPanel.show(),b=a.outerWidth(),c=a.outerHeight();a.css({marginTop:-c/2,marginLeft:-b/2}),this._shader.show()},hide:function(){this._loadPanel.hide(),this._shader.hide()}},a.LoadIndicator=d}(jsGrid,jQuery),function(a,b,c){function d(a){this._grid=a}function e(a){this._grid=a,this._itemsCount=0}d.prototype={firstDisplayIndex:function(){var a=this._grid;return a.option("paging")?(a.option("pageIndex")-1)*a.option("pageSize"):0},lastDisplayIndex:function(){var a=this._grid,b=a.option("data").length;return a.option("paging")?Math.min(a.option("pageIndex")*a.option("pageSize"),b):b},itemsCount:function(){return this._grid.option("data").length},openPage:function(a){this._grid.refresh()},loadParams:function(){return{}},sort:function(){return this._grid._sortData(),this._grid.refresh(),b.Deferred().resolve().promise()},reset:function(){return this._grid.refresh(),b.Deferred().resolve().promise()},finishLoad:function(a){this._grid.option("data",a)},finishInsert:function(a,b){var c=this._grid;switch(b){case"top":c.option("data").unshift(a);break;case"bottom":default:c.option("data").push(a)}c.refresh()},finishDelete:function(a,b){var c=this._grid;c.option("data").splice(b,1),c.reset()}},e.prototype={firstDisplayIndex:function(){return 0},lastDisplayIndex:function(){return this._grid.option("data").length},itemsCount:function(){return this._itemsCount},openPage:function(a){this._grid.loadData()},loadParams:function(){var a=this._grid;return{pageIndex:a.option("pageIndex"),pageSize:a.option("pageSize")}},reset:function(){return this._grid.loadData()},sort:function(){return this._grid.loadData()},finishLoad:function(a){this._itemsCount=a.itemsCount,this._grid.option("data",a.data)},finishInsert:function(a){this._grid.search()},finishDelete:function(a,b){this._grid.search()}},a.loadStrategies={DirectLoadingStrategy:d,PageLoadingStrategy:e}}(jsGrid,jQuery),function(a,b,c){var d=function(a){return void 0!==a&&null!==a},e={string:function(a,b){return d(a)||d(b)?d(a)?d(b)?(""+a).localeCompare(""+b):1:-1:0},number:function(a,b){return a-b},date:function(a,b){return a-b},numberAsString:function(a,b){return parseFloat(a)-parseFloat(b)}};a.sortStrategies=e}(jsGrid,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={_init:function(a){b.extend(!0,this,a)},validate:function(a){var c=[];return b.each(this._normalizeRules(a.rules),function(d,e){if(!e.validator(a.value,a.item,e.param)){var f=b.isFunction(e.message)?e.message(a.value,a.item):e.message;c.push(f)}}),c},_normalizeRules:function(a){return b.isArray(a)||(a=[a]),b.map(a,b.proxy(function(a){return this._normalizeRule(a)},this))},_normalizeRule:function(a){if("string"==typeof a&&(a={validator:a}),b.isFunction(a)&&(a={validator:a}),!b.isPlainObject(a))throw Error("wrong validation config specified");return a=b.extend({},a),b.isFunction(a.validator)?a:this._applyNamedValidator(a,a.validator)},_applyNamedValidator:function(a,c){delete a.validator;var d=e[c];if(!d)throw Error('unknown validator "'+c+'"');return b.isFunction(d)&&(d={validator:d}),b.extend({},d,a)}},a.Validation=d;var e={required:{message:"Field is required",validator:function(a){return a!==c&&null!==a&&""!==a}},rangeLength:{message:"Field value length is out of the defined range",validator:function(a,b,c){return a.length>=c[0]&&a.length<=c[1]}},minLength:{message:"Field value is too short",validator:function(a,b,c){return a.length>=c}},maxLength:{message:"Field value is too long",validator:function(a,b,c){return a.length<=c}},pattern:{message:"Field value is not matching the defined pattern",validator:function(a,b,c){return"string"==typeof c&&(c=new RegExp("^(?:"+c+")$")),c.test(a)}},range:{message:"Field value is out of the defined range",validator:function(a,b,c){return a>=c[0]&&a<=c[1]}},min:{message:"Field value is too small",validator:function(a,b,c){return a>=c}},max:{message:"Field value is too large",validator:function(a,b,c){return a<=c}}};a.validators=e}(jsGrid,jQuery),function(a,b,c){function d(a){b.extend(!0,this,a),this.sortingFunc=this._getSortingFunc()}d.prototype={name:"",title:null,css:"",align:"",width:100,visible:!0,filtering:!0,inserting:!0,editing:!0,sorting:!0,sorter:"string",headerTemplate:function(){return this.title===c||null===this.title?this.name:this.title},itemTemplate:function(a,b){return a},filterTemplate:function(){return""},insertTemplate:function(){return""},editTemplate:function(a,b){return this._value=a,this.itemTemplate(a,b)},filterValue:function(){return""},insertValue:function(){return""},editValue:function(){return this._value},_getSortingFunc:function(){var c=this.sorter;if(b.isFunction(c))return c;if("string"==typeof c)return a.sortStrategies[c];throw Error('wrong sorter for the field "'+this.name+'"!')}},a.Field=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({autosearch:!0,readOnly:!1,filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createTextBox();return this.autosearch&&b.on("keypress",function(b){13===b.which&&(a.search(),b.preventDefault())}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createTextBox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextBox();return b.val(a),b},filterValue:function(){return this.filterControl.val()},insertValue:function(){return this.insertControl.val()},editValue:function(){return this.editControl.val()},_createTextBox:function(){return b("<input>").attr("type","text").prop("readonly",!!this.readOnly)}}),a.fields.text=a.TextField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({sorter:"number",align:"right",readOnly:!1,filterValue:function(){return this.filterControl.val()?parseInt(this.filterControl.val()||0,10):c},insertValue:function(){return this.insertControl.val()?parseInt(this.insertControl.val()||0,10):c},editValue:function(){return this.editControl.val()?parseInt(this.editControl.val()||0,10):c},_createTextBox:function(){return b("<input>").attr("type","number").prop("readonly",!!this.readOnly)}}),a.fields.number=a.NumberField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({insertTemplate:function(){return this.inserting?this.insertControl=this._createTextArea():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextArea();return b.val(a),b},_createTextArea:function(){return b("<textarea>").prop("readonly",!!this.readOnly)}}),a.fields.textarea=a.TextAreaField=d}(jsGrid,jQuery),function(a,b,c){function d(a){if(this.items=[],this.selectedIndex=-1,this.valueField="",this.textField="",a.valueField&&a.items.length){var b=a.items[0][a.valueField];this.valueType=typeof b===f?f:g}this.sorter=this.valueType,e.call(this,a)}var e=a.NumberField,f="number",g="string";d.prototype=new e({align:"center",valueType:f,itemTemplate:function(a){var d,e=this.items,f=this.valueField,g=this.textField;d=f?b.grep(e,function(b,c){return b[f]===a})[0]||{}:e[a];var h=g?d[g]:d;return h===c||null===h?"":h},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createSelect();return this.autosearch&&b.on("change",function(b){a.search()}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createSelect():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createSelect();return a!==c&&b.val(a),b},filterValue:function(){var a=this.filterControl.val();return this.valueType===f?parseInt(a||0,10):a},insertValue:function(){var a=this.insertControl.val();return this.valueType===f?parseInt(a||0,10):a},editValue:function(){var a=this.editControl.val();return this.valueType===f?parseInt(a||0,10):a},_createSelect:function(){var a=b("<select>"),c=this.valueField,d=this.textField,e=this.selectedIndex;return b.each(this.items,function(e,f){var g=c?f[c]:e,h=d?f[d]:f;b("<option>").attr("value",g).text(h).appendTo(a)}),a.prop("disabled",!!this.readOnly),a.prop("selectedIndex",e),a}}),a.fields.select=a.SelectField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({sorter:"number",align:"center",autosearch:!0,itemTemplate:function(a){return this._createCheckbox().prop({checked:a,disabled:!0})},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,c=this.filterControl=this._createCheckbox();return c.prop({readOnly:!0,indeterminate:!0}),c.on("click",function(){var a=b(this);a.prop("readOnly")?a.prop({checked:!1,readOnly:!1}):a.prop("checked")||a.prop({readOnly:!0,indeterminate:!0})}),this.autosearch&&c.on("click",function(){a.search()}),c},insertTemplate:function(){return this.inserting?this.insertControl=this._createCheckbox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createCheckbox();return b.prop("checked",a),b},filterValue:function(){return this.filterControl.get(0).indeterminate?c:this.filterControl.is(":checked")},insertValue:function(){return this.insertControl.is(":checked")},editValue:function(){return this.editControl.is(":checked")},_createCheckbox:function(){return b("<input>").attr("type","checkbox")}}),a.fields.checkbox=a.CheckboxField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a),this._configInitialized=!1}var e=a.Field;d.prototype=new e({css:"jsgrid-control-field",align:"center",width:50,filtering:!1,inserting:!1,editing:!1,sorting:!1,buttonClass:"jsgrid-button",modeButtonClass:"jsgrid-mode-button",modeOnButtonClass:"jsgrid-mode-on-button",searchModeButtonClass:"jsgrid-search-mode-button",insertModeButtonClass:"jsgrid-insert-mode-button",editButtonClass:"jsgrid-edit-button",deleteButtonClass:"jsgrid-delete-button",searchButtonClass:"jsgrid-search-button",clearFilterButtonClass:"jsgrid-clear-filter-button",insertButtonClass:"jsgrid-insert-button",updateButtonClass:"jsgrid-update-button",cancelEditButtonClass:"jsgrid-cancel-edit-button",searchModeButtonTooltip:"Switch to searching",insertModeButtonTooltip:"Switch to inserting",editButtonTooltip:"Edit",deleteButtonTooltip:"Delete",searchButtonTooltip:"Search",clearFilterButtonTooltip:"Clear filter",insertButtonTooltip:"Insert",updateButtonTooltip:"Update",cancelEditButtonTooltip:"Cancel edit",editButton:!0,deleteButton:!0,clearFilterButton:!0,modeSwitchButton:!0,_initConfig:function(){this._hasFiltering=this._grid.filtering,this._hasInserting=this._grid.inserting,this._hasInserting&&this.modeSwitchButton&&(this._grid.inserting=!1),this._configInitialized=!0},headerTemplate:function(){this._configInitialized||this._initConfig();var a=this._hasFiltering,b=this._hasInserting;return this.modeSwitchButton&&(a||b)?a&&!b?this._createFilterSwitchButton():b&&!a?this._createInsertSwitchButton():this._createModeSwitchButton():""},itemTemplate:function(a,c){var d=b([]);return this.editButton&&(d=d.add(this._createEditButton(c))),this.deleteButton&&(d=d.add(this._createDeleteButton(c))),d},filterTemplate:function(){var a=this._createSearchButton();return this.clearFilterButton?a.add(this._createClearFilterButton()):a},insertTemplate:function(){return this._createInsertButton()},editTemplate:function(){return this._createUpdateButton().add(this._createCancelEditButton())},_createFilterSwitchButton:function(){return this._createOnOffSwitchButton("filtering",this.searchModeButtonClass,!0)},_createInsertSwitchButton:function(){return this._createOnOffSwitchButton("inserting",this.insertModeButtonClass,!1)},_createOnOffSwitchButton:function(a,c,d){var e=d,f=b.proxy(function(){g.toggleClass(this.modeOnButtonClass,e)},this),g=this._createGridButton(this.modeButtonClass+" "+c,"",function(b){e=!e,b.option(a,e),f()});return f(),g},_createModeSwitchButton:function(){var a=!1,c=b.proxy(function(){d.attr("title",a?this.searchModeButtonTooltip:this.insertModeButtonTooltip).toggleClass(this.insertModeButtonClass,!a).toggleClass(this.searchModeButtonClass,a)},this),d=this._createGridButton(this.modeButtonClass,"",function(b){a=!a,b.option("inserting",a),b.option("filtering",!a),c()});return c(),d},_createEditButton:function(a){return this._createGridButton(this.editButtonClass,this.editButtonTooltip,function(b,c){b.editItem(a),c.stopPropagation()})},_createDeleteButton:function(a){return this._createGridButton(this.deleteButtonClass,this.deleteButtonTooltip,function(b,c){b.deleteItem(a),c.stopPropagation()})},_createSearchButton:function(){return this._createGridButton(this.searchButtonClass,this.searchButtonTooltip,function(a){a.search()})},_createClearFilterButton:function(){return this._createGridButton(this.clearFilterButtonClass,this.clearFilterButtonTooltip,function(a){a.clearFilter()})},_createInsertButton:function(){return this._createGridButton(this.insertButtonClass,this.insertButtonTooltip,function(a){a.insertItem().done(function(){a.clearInsert()})})},_createUpdateButton:function(){return this._createGridButton(this.updateButtonClass,this.updateButtonTooltip,function(a,b){a.updateItem(),b.stopPropagation()})},_createCancelEditButton:function(){return this._createGridButton(this.cancelEditButtonClass,this.cancelEditButtonTooltip,function(a,b){a.cancelEdit(),b.stopPropagation()})},_createGridButton:function(a,c,d){var e=this._grid;return b("<input>").addClass(this.buttonClass).addClass(a).attr({type:"button",title:c}).on("click",function(a){d(e,a)})},editValue:function(){return""}}),a.fields.control=a.ControlField=d}(jsGrid,jQuery); \ No newline at end of file +!function(a,b,c){function d(a,c){var d=b(a);d.data(f,this),this._container=d,this.data=[],this.fields=[],this._editingRow=null,this._sortField=null,this._sortOrder=i,this._firstDisplayingPage=1,this._init(c),this.render()}var e="JSGrid",f=e,g="JSGridItem",h="JSGridEditRow",i="asc",j="desc",k="{first}",l="{pages}",m="{prev}",n="{next}",o="{last}",p="{pageIndex}",q="{pageCount}",r="{itemCount}",s="javascript:void(0);",t=function(a,c){return b.isFunction(a)?a.apply(c,b.makeArray(arguments).slice(2)):a},u=function(a){var c=b.Deferred();return a&&a.then?a.then(function(){c.resolve.apply(c,arguments)},function(){c.reject.apply(c,arguments)}):c.resolve(a),c.promise()},v={loadData:b.noop,insertItem:b.noop,updateItem:b.noop,deleteItem:b.noop};d.prototype={width:"auto",height:"auto",updateOnResize:!0,rowClass:b.noop,rowRenderer:null,rowClick:function(a){this.editing&&this.editItem(b(a.event.target).closest("tr"))},rowDoubleClick:b.noop,noDataContent:"Not found",noDataRowClass:"jsgrid-nodata-row",heading:!0,headerRowRenderer:null,headerRowClass:"jsgrid-header-row",headerCellClass:"jsgrid-header-cell",filtering:!1,filterRowRenderer:null,filterRowClass:"jsgrid-filter-row",inserting:!1,insertRowRenderer:null,insertRowClass:"jsgrid-insert-row",editing:!1,editRowRenderer:null,editRowClass:"jsgrid-edit-row",confirmDeleting:!0,deleteConfirm:"Are you sure?",selecting:!0,selectedRowClass:"jsgrid-selected-row",oddRowClass:"jsgrid-row",evenRowClass:"jsgrid-alt-row",cellClass:"jsgrid-cell",sorting:!1,sortableClass:"jsgrid-header-sortable",sortAscClass:"jsgrid-header-sort jsgrid-header-sort-asc",sortDescClass:"jsgrid-header-sort jsgrid-header-sort-desc",paging:!1,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",pagerNavButtonInactiveClass:"jsgrid-pager-nav-inactive-button",pageClass:"jsgrid-pager-page",currentPageClass:"jsgrid-pager-current-page",customLoading:!1,pageLoading:!1,autoload:!1,controller:v,loadIndication:!0,loadIndicationDelay:500,loadMessage:"Please, wait...",loadShading:!0,invalidMessage:"Invalid data entered!",invalidNotify:function(c){var d=b.map(c.errors,function(a){return a.message||null});a.alert([this.invalidMessage].concat(d).join("\n"))},onInit:b.noop,onRefreshing:b.noop,onRefreshed:b.noop,onPageChanged:b.noop,onItemDeleting:b.noop,onItemDeleted:b.noop,onItemInserting:b.noop,onItemInserted:b.noop,onItemEditing:b.noop,onItemUpdating:b.noop,onItemUpdated:b.noop,onItemInvalid:b.noop,onDataLoading:b.noop,onDataLoaded:b.noop,onOptionChanging:b.noop,onOptionChanged:b.noop,onError:b.noop,invalidClass:"jsgrid-invalid",containerClass:"jsgrid",tableClass:"jsgrid-table",gridHeaderClass:"jsgrid-grid-header",gridBodyClass:"jsgrid-grid-body",_init:function(a){b.extend(this,a),this._initLoadStrategy(),this._initController(),this._initFields(),this._attachWindowLoadResize(),this._attachWindowResizeCallback(),this._callEventHandler(this.onInit)},loadStrategy:function(){return this.pageLoading?new jsGrid.loadStrategies.PageLoadingStrategy(this):new jsGrid.loadStrategies.DirectLoadingStrategy(this)},_initLoadStrategy:function(){this._loadStrategy=t(this.loadStrategy,this)},_initController:function(){this._controller=b.extend({},v,t(this.controller,this))},renderTemplate:function(a,b,d){args=[];for(var e in d)args.push(d[e]);return args.unshift(a,b),a=t.apply(null,args),a===c||null===a?"":a},loadIndicator:function(a){return new jsGrid.LoadIndicator(a)},validation:function(a){return jsGrid.Validation&&new jsGrid.Validation(a)},_initFields:function(){var a=this;a.fields=b.map(a.fields,function(c){if(b.isPlainObject(c)){var d=c.type&&jsGrid.fields[c.type]||jsGrid.Field;c=new d(c)}return c._grid=a,c})},_attachWindowLoadResize:function(){b(a).on("load",b.proxy(this._refreshSize,this))},_attachWindowResizeCallback:function(){this.updateOnResize&&b(a).on("resize",b.proxy(this._refreshSize,this))},_detachWindowResizeCallback:function(){b(a).off("resize",this._refreshSize)},option:function(a,b){var c,d;return 1===arguments.length?this[a]:(c={option:a,oldValue:this[a],newValue:b},this._callEventHandler(this.onOptionChanging,c),this._handleOptionChange(c.option,c.newValue),d={option:c.option,value:c.newValue},void this._callEventHandler(this.onOptionChanged,d))},fieldOption:function(a,b,c){return a=this._normalizeField(a),2===arguments.length?a[b]:(a[b]=c,void this._renderGrid())},_handleOptionChange:function(a,b){switch(this[a]=b,a){case"width":case"height":this._refreshSize();break;case"rowClass":case"rowRenderer":case"rowClick":case"rowDoubleClick":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":case"pagerRenderer":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"loadStrategy":case"pageLoading":this._initLoadStrategy(),this.search();break;case"pageIndex":this.openPage(b);break;case"pageSize":this.refresh(),this.search();break;case"editRowRenderer":case"editRowClass":this.cancelEdit();break;case"updateOnResize":this._detachWindowResizeCallback(),this._attachWindowResizeCallback();break;case"invalidNotify":case"invalidMessage":break;default:this.render()}},destroy:function(){this._detachWindowResizeCallback(),this._clear(),this._container.removeData(f)},render:function(){return this._renderGrid(),this.autoload?this.loadData():b.Deferred().resolve().promise()},_renderGrid: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._validation=this._createValidation(),this.refresh()},_createLoadIndicator:function(){return t(this.loadIndicator,this,{message:this.loadMessage,shading:this.loadShading,container:this._container})},_createValidation:function(){return t(this.validation,this)},_clear:function(){this.cancelEdit(),clearTimeout(this._loadingTimer),this._pagerContainer&&this._pagerContainer.empty(),this._container.empty().css({position:"",width:"",height:""})},_createHeader:function(){var a=this._headerRow=this._createHeaderRow(),c=this._filterRow=this._createFilterRow(),d=this._insertRow=this._createInsertRow(),e=this._headerGrid=b("<table>").addClass(this.tableClass).append(a).append(c).append(d),f=this._header=b("<div>").addClass(this.gridHeaderClass).addClass(this._scrollBarWidth()?"jsgrid-header-scrollbar":"").append(e);return f},_createBody:function(){var a=this._content=b("<tbody>"),c=this._bodyGrid=b("<table>").addClass(this.tableClass).append(a),d=this._body=b("<div>").addClass(this.gridBodyClass).append(c).on("scroll",b.proxy(function(a){this._header.scrollLeft(a.target.scrollLeft)},this));return d},_createPagerContainer:function(){var a=this.pagerContainer||b("<div>").appendTo(this._container);return b(a).addClass(this.pagerContainerClass)},_eachField:function(a){var c=this;b.each(this.fields,function(b,d){d.visible&&a.call(c,d,b)})},_createHeaderRow:function(){if(b.isFunction(this.headerRowRenderer))return b(this.renderTemplate(this.headerRowRenderer,this));var a=b("<tr>").addClass(this.headerRowClass);return this._eachField(function(c,d){var e=this._prepareCell("<th>",c,"headercss",this.headerCellClass).append(this.renderTemplate(c.headerTemplate,c)).appendTo(a);this.sorting&&c.sorting&&e.addClass(this.sortableClass).on("click",b.proxy(function(){this.sort(d)},this))}),a},_prepareCell:function(a,c,d,e){return b(a).css("width",c.width).addClass(e||this.cellClass).addClass(d&&c[d]||c.css).addClass(c.align?"jsgrid-align-"+c.align:"")},_createFilterRow:function(){if(b.isFunction(this.filterRowRenderer))return b(this.renderTemplate(this.filterRowRenderer,this));var a=b("<tr>").addClass(this.filterRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"filtercss").append(this.renderTemplate(b.filterTemplate,b)).appendTo(a)}),a},_createInsertRow:function(){if(b.isFunction(this.insertRowRenderer))return b(this.renderTemplate(this.insertRowRenderer,this));var a=b("<tr>").addClass(this.insertRowClass);return this._eachField(function(b){this._prepareCell("<td>",b,"insertcss").append(this.renderTemplate(b.insertTemplate,b)).appendTo(a)}),a},_callEventHandler:function(a,c){return a.call(this,b.extend(c,{grid:this})),c},reset:function(){return this._resetSorting(),this._resetPager(),this._loadStrategy.reset()},_resetPager:function(){this._firstDisplayingPage=1,this._setPage(1)},_resetSorting:function(){this._sortField=null,this._sortOrder=i,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 a=this._content;if(a.empty(),!this.data.length)return a.append(this._createNoDataRow()),this;for(var b=this._loadStrategy.firstDisplayIndex(),c=this._loadStrategy.lastDisplayIndex(),d=b;c>d;d++){var e=this.data[d];a.append(this._createRow(e,d))}},_createNoDataRow:function(){var a=0;return this._eachField(function(){a++}),b("<tr>").addClass(this.noDataRowClass).append(b("<td>").addClass(this.cellClass).attr("colspan",a).append(this.renderTemplate(this.noDataContent,this)))},_createRow:function(a,c){var d;return b.isFunction(this.rowRenderer)?d=this.renderTemplate(this.rowRenderer,this,{item:a,itemIndex:c}):(d=b("<tr>"),this._renderCells(d,a)),d.addClass(this._getRowClasses(a,c)).data(g,a).on("click",b.proxy(function(b){this.rowClick({item:a,itemIndex:c,event:b})},this)).on("dblclick",b.proxy(function(b){this.rowDoubleClick({item:a,itemIndex:c,event:b})},this)),this.selecting&&this._attachRowHover(d),d},_getRowClasses:function(a,b){var c=[];return c.push((b+1)%2?this.oddRowClass:this.evenRowClass),c.push(t(this.rowClass,this,a,b)),c.join(" ")},_attachRowHover:function(a){var c=this.selectedRowClass;a.hover(function(){b(this).addClass(c)},function(){b(this).removeClass(c)})},_renderCells:function(a,b){return this._eachField(function(c){a.append(this._createCell(b,c))}),this},_createCell:function(a,c){var d,e=this._getItemFieldValue(a,c),f={value:e,item:a};return d=b.isFunction(c.cellRenderer)?this.renderTemplate(c.cellRenderer,c,f):b("<td>").append(this.renderTemplate(c.itemTemplate||e,c,f)),this._prepareCell(d,c)},_getItemFieldValue:function(a,b){for(var c=b.name.split("."),d=a[c.shift()];d&&c.length;)d=d[c.shift()];return d},_setItemFieldValue:function(a,b,c){for(var d=b.name.split("."),e=a,f=d[0];e&&d.length;)a=e,f=d.shift(),e=a[f];if(!e)for(;d.length;)a=a[f]={},f=d.shift();a[f]=c},sort:function(a,c){return b.isPlainObject(a)&&(c=a.order,a=a.field),this._clearSortingCss(),this._setSortingParams(a,c),this._setSortingCss(),this._loadStrategy.sort()},_clearSortingCss:function(){this._headerRow.find("th").removeClass(this.sortAscClass).removeClass(this.sortDescClass)},_setSortingParams:function(a,b){a=this._normalizeField(a),b=b||(this._sortField===a?this._reversedSortOrder(this._sortOrder):i),this._sortField=a,this._sortOrder=b},_normalizeField:function(a){return b.isNumeric(a)?this.fields[a]:"string"==typeof a?b.grep(this.fields,function(b){return b.name===a})[0]:a},_reversedSortOrder:function(a){return a===i?j:i},_setSortingCss:function(){var a=this._visibleFieldIndex(this._sortField);this._headerRow.find("th").eq(a).addClass(this._sortOrder===i?this.sortAscClass:this.sortDescClass)},_visibleFieldIndex:function(a){return b.inArray(a,b.grep(this.fields,function(a){return a.visible}))},_sortData:function(){var a=this._sortFactor(),b=this._sortField;b&&this.data.sort(function(c,d){return a*b.sortingFunc(c[b.name],d[b.name])})},_sortFactor:function(){return this._sortOrder===i?1:-1},_itemsCount:function(){return this._loadStrategy.itemsCount()},_pagesCount:function(){var a=this._itemsCount(),b=this.pageSize;return Math.floor(a/b)+(a%b?1:0)},_refreshPager:function(){var a=this._pagerContainer;a.empty(),this.paging&&a.append(this._createPager());var b=this.paging&&this._pagesCount()>1;a.toggle(b)},_createPager:function(){var a;return a=b.isFunction(this.pagerRenderer)?b(this.pagerRenderer({pageIndex:this.pageIndex,pageCount:this._pagesCount()})):b("<div>").append(this._createPagerByFormat()),a.addClass(this.pagerClass),a},_createPagerByFormat:function(){var a=this.pageIndex,c=this._pagesCount(),d=this._itemsCount(),e=this.pagerFormat.split(" ");return b.map(e,b.proxy(function(e){var f=e;return e===l?f=this._createPages():e===k?f=this._createPagerNavButton(this.pageFirstText,1,a>1):e===m?f=this._createPagerNavButton(this.pagePrevText,a-1,a>1):e===n?f=this._createPagerNavButton(this.pageNextText,a+1,c>a):e===o?f=this._createPagerNavButton(this.pageLastText,c,c>a):e===p?f=a:e===q?f=c:e===r&&(f=d),b.isArray(f)?f.concat([" "]):[f," "]},this))},_createPages:function(){var a=this._pagesCount(),b=this.pageButtonCount,c=this._firstDisplayingPage,d=[];c>1&&d.push(this._createPagerPageNavButton(this.pageNavigatorPrevText,this.showPrevPages));for(var e=0,f=c;b>e&&a>=f;e++,f++)d.push(f===this.pageIndex?this._createPagerCurrentPage():this._createPagerPage(f));return a>c+b-1&&d.push(this._createPagerPageNavButton(this.pageNavigatorNextText,this.showNextPages)),d},_createPagerNavButton:function(a,c,d){return this._createPagerButton(a,this.pagerNavButtonClass+(d?"":" "+this.pagerNavButtonInactiveClass),d?function(){this.openPage(c)}:b.noop)},_createPagerPageNavButton:function(a,b){return this._createPagerButton(a,this.pagerNavButtonClass,b)},_createPagerPage:function(a){return this._createPagerButton(a,this.pageClass,function(){this.openPage(a)})},_createPagerButton:function(a,c,d){var e=b("<a>").attr("href",s).html(a).on("click",b.proxy(d,this));return b("<span>").addClass(c).append(e)},_createPagerCurrentPage:function(){return b("<span>").addClass(this.pageClass).addClass(this.currentPageClass).text(this.pageIndex)},_refreshSize:function(){this._refreshHeight(),this._refreshWidth()},_refreshWidth:function(){var a="auto"===this.width?this._getAutoWidth():this.width;this._container.width(a)},_getAutoWidth:function(){var a=this._headerGrid,b=this._header;a.width("auto");var c=a.outerWidth(),d=b.outerWidth()-b.innerWidth();return a.width(""),c+d},_scrollBarWidth:function(){var a;return function(){if(a===c){var d=b("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>"),e=b("<div style='height:100px;'></div>");d.append(e).appendTo("body");var f=e.innerWidth();d.css("overflow-y","auto");var g=e.innerWidth();d.remove(),a=f-g}return a}}(),_refreshHeight:function(){var a,b=this._container,c=this._pagerContainer,d=this.height;b.height(d),"auto"!==d&&(d=b.height(),a=this._header.outerHeight(!0),c.parents(b).length&&(a+=c.outerHeight(!0)),this._body.outerHeight(d-a))},showPrevPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount;this._firstDisplayingPage=a>b?a-b:1,this._refreshPager()},showNextPages:function(){var a=this._firstDisplayingPage,b=this.pageButtonCount,c=this._pagesCount();this._firstDisplayingPage=a+2*b>c?c-b+1:a+b,this._refreshPager()},openPage:function(a){1>a||a>this._pagesCount()||(this._setPage(a),this._loadStrategy.openPage(a))},_setPage:function(a){var b=this._firstDisplayingPage,c=this.pageButtonCount;this.pageIndex=a,b>a&&(this._firstDisplayingPage=a),a>b+c-1&&(this._firstDisplayingPage=a-c+1),this._callEventHandler(this.onPageChanged,{pageIndex:a})},_controllerCall:function(a,c,d,e){if(d)return b.Deferred().reject().promise();this._showLoading();var f=this._controller;if(!f||!f[a])throw Error("controller has no method '"+a+"'");return u(f[a](c)).done(b.proxy(e,this)).fail(b.proxy(this._errorHandler,this)).always(b.proxy(this._hideLoading,this))},_errorHandler:function(){this._callEventHandler(this.onError,{args:b.makeArray(arguments)})},_showLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadingTimer=setTimeout(b.proxy(function(){this._loadIndicator.show()},this),this.loadIndicationDelay))},_hideLoading:function(){this.loadIndication&&(clearTimeout(this._loadingTimer),this._loadIndicator.hide())},search:function(a){return this._resetSorting(),this._resetPager(),this.loadData(a)},loadData:function(a){a=a||(this.filtering?this.getFilter():{}),b.extend(a,this._loadStrategy.loadParams(),this._sortingParams());var c=this._callEventHandler(this.onDataLoading,{filter:a});return this._controllerCall("loadData",a,c.cancel,function(a){a&&(this._loadStrategy.finishLoad(a),this._callEventHandler(this.onDataLoaded,{data:a}))})},getFilter:function(){var a={};return this._eachField(function(b){b.filtering&&this._setItemFieldValue(a,b,b.filterValue())}),a},_sortingParams:function(){return this.sorting&&this._sortField?{sortField:this._sortField.name,sortOrder:this._sortOrder}:{}},getSorting:function(){var a=this._sortingParams();return{field:a.sortField,order:a.sortOrder}},clearFilter:function(){var a=this._createFilterRow();return this._filterRow.replaceWith(a),this._filterRow=a,this.search()},insertItem:function(a){var c=a||this._getValidatedInsertItem();if(!c)return b.Deferred().reject().promise();var d=this._callEventHandler(this.onItemInserting,{item:c});return this._controllerCall("insertItem",c,d.cancel,function(a){a=a||c,this._loadStrategy.finishInsert(a),this._callEventHandler(this.onItemInserted,{item:a})})},_getValidatedInsertItem:function(){var a=this._getInsertItem();return this._validateItem(a,this._insertRow)?a:null},_getInsertItem:function(){var a={};return this._eachField(function(b){b.inserting&&this._setItemFieldValue(a,b,b.insertValue())}),a},_validateItem:function(a,c){var d=[],e={item:a,itemIndex:this._rowIndex(c),row:c};if(this._eachField(function(f){if(f.validate&&(c!==this._insertRow||f.inserting)&&(c!==this._getEditRow()||f.editing)){var g=this._getItemFieldValue(a,f),h=this._validation.validate(b.extend({value:g,rules:f.validate},e));this._setCellValidity(c.children().eq(this._visibleFieldIndex(f)),h),h.length&&d.push.apply(d,b.map(h,function(a){return{field:f,message:a}}))}}),!d.length)return!0;var f=b.extend({errors:d},e);return this._callEventHandler(this.onItemInvalid,f),this.invalidNotify(f),!1},_setCellValidity:function(a,b){a.toggleClass(this.invalidClass,!!b.length).attr("title",b.join("\n"))},clearInsert:function(){var a=this._createInsertRow();this._insertRow.replaceWith(a),this._insertRow=a,this.refresh()},editItem:function(a){var b=this.rowByItem(a);b.length&&this._editRow(b)},rowByItem:function(a){return a.jquery||a.nodeType?b(a):this._content.find("tr").filter(function(){return b.data(this,g)===a})},_editRow:function(a){if(this.editing){var b=a.data(g),c=this._callEventHandler(this.onItemEditing,{row:a,item:b,itemIndex:this._itemIndex(b)});if(!c.cancel){this._editingRow&&this.cancelEdit();var d=this._createEditRow(b);this._editingRow=a,a.hide(),d.insertBefore(a),a.data(h,d)}}},_createEditRow:function(a){if(b.isFunction(this.editRowRenderer))return b(this.renderTemplate(this.editRowRenderer,this,{item:a,itemIndex:this._itemIndex(a)}));var c=b("<tr>").addClass(this.editRowClass);return this._eachField(function(b){var d=this._getItemFieldValue(a,b);this._prepareCell("<td>",b,"editcss").append(this.renderTemplate(b.editTemplate||"",b,{value:d,item:a})).appendTo(c)}),c},updateItem:function(a,b){1===arguments.length&&(b=a);var c=a?this.rowByItem(a):this._editingRow;return(b=b||this._getValidatedEditedItem())?this._updateRow(c,b):void 0},_getValidatedEditedItem:function(){var a=this._getEditedItem();return this._validateItem(a,this._getEditRow())?a:null},_updateRow:function(a,c){var d=a.data(g),e=this._itemIndex(d),f=b.extend(!0,{},d,c),h=this._callEventHandler(this.onItemUpdating,{row:a,item:f,itemIndex:e,previousItem:d});return this._controllerCall("updateItem",f,h.cancel,function(g){var h=b.extend(!0,{},d);f=g||b.extend(!0,d,c);var i=this._finishUpdate(a,f,e);this._callEventHandler(this.onItemUpdated,{row:i,item:f,itemIndex:e,previousItem:h})})},_rowIndex:function(a){return this._content.children().index(b(a))},_itemIndex:function(a){return b.inArray(a,this.data)},_finishUpdate:function(a,b,c){this.cancelEdit(),this.data[c]=b;var d=this._createRow(b,c);return a.replaceWith(d),d},_getEditedItem:function(){var a={};return this._eachField(function(b){b.editing&&this._setItemFieldValue(a,b,b.editValue())}),a},cancelEdit:function(){this._editingRow&&(this._getEditRow().remove(),this._editingRow.show(),this._editingRow=null)},_getEditRow:function(){return this._editingRow&&this._editingRow.data(h)},deleteItem:function(b){var c=this.rowByItem(b);if(c.length&&(!this.confirmDeleting||a.confirm(t(this.deleteConfirm,this,c.data(g)))))return this._deleteRow(c)},_deleteRow:function(a){var b=a.data(g),c=this._itemIndex(b),d=this._callEventHandler(this.onItemDeleting,{row:a,item:b,itemIndex:c});return this._controllerCall("deleteItem",b,d.cancel,function(){this._loadStrategy.finishDelete(b,c),this._callEventHandler(this.onItemDeleted,{row:a,item:b,itemIndex:c})})}},b.fn.jsGrid=function(a){var e=b.makeArray(arguments),g=e.slice(1),h=this;return this.each(function(){var e,i=b(this),j=i.data(f);if(j)if("string"==typeof a){if(e=j[a].apply(j,g),e!==c&&e!==j)return h=e,!1}else j._detachWindowResizeCallback(),j._init(a),j.render();else new d(i,a)}),h};var w={},x=function(a){var c;b.isPlainObject(a)?c=d.prototype:(c=w[a].prototype,a=arguments[1]||{}),b.extend(c,a)},y={},z=function(a){var c=b.isPlainObject(a)?a:y[a];if(!c)throw Error("unknown locale "+a);A(jsGrid,c)},A=function(a,c){b.each(c,function(c,d){return b.isPlainObject(d)?void A(a[c]||a[c[0].toUpperCase()+c.slice(1)],d):void(a.hasOwnProperty(c)?a[c]=d:a.prototype[c]=d)})};a.jsGrid={Grid:d,fields:w,setDefaults:x,locales:y,locale:z,version:"1.5.3"}}(window,jQuery),function(a,b){function c(a){this._init(a)}c.prototype={container:"body",message:"Loading...",shading:!0,zIndex:1e3,shaderClass:"jsgrid-load-shader",loadPanelClass:"jsgrid-load-panel",_init:function(a){b.extend(!0,this,a),this._initContainer(),this._initShader(),this._initLoadPanel()},_initContainer:function(){this._container=b(this.container)},_initShader:function(){this.shading&&(this._shader=b("<div>").addClass(this.shaderClass).hide().css({position:"absolute",top:0,right:0,bottom:0,left:0,zIndex:this.zIndex}).appendTo(this._container))},_initLoadPanel:function(){this._loadPanel=b("<div>").addClass(this.loadPanelClass).text(this.message).hide().css({position:"absolute",top:"50%",left:"50%",zIndex:this.zIndex}).appendTo(this._container)},show:function(){var a=this._loadPanel.show(),b=a.outerWidth(),c=a.outerHeight();a.css({marginTop:-c/2,marginLeft:-b/2}),this._shader.show()},hide:function(){this._loadPanel.hide(),this._shader.hide()}},a.LoadIndicator=c}(jsGrid,jQuery),function(a,b){function c(a){this._grid=a}function d(a){this._grid=a,this._itemsCount=0}c.prototype={firstDisplayIndex:function(){var a=this._grid;return a.option("paging")?(a.option("pageIndex")-1)*a.option("pageSize"):0},lastDisplayIndex:function(){var a=this._grid,b=a.option("data").length;return a.option("paging")?Math.min(a.option("pageIndex")*a.option("pageSize"),b):b},itemsCount:function(){return this._grid.option("data").length},openPage:function(){this._grid.refresh()},loadParams:function(){return{}},sort:function(){return this._grid._sortData(),this._grid.refresh(),b.Deferred().resolve().promise()},reset:function(){return this._grid.refresh(),b.Deferred().resolve().promise()},finishLoad:function(a){this._grid.option("data",a)},finishInsert:function(a){var b=this._grid;b.option("data").push(a),b.refresh()},finishDelete:function(a,b){var c=this._grid;c.option("data").splice(b,1),c.reset()}},d.prototype={firstDisplayIndex:function(){return 0},lastDisplayIndex:function(){return this._grid.option("data").length},itemsCount:function(){return this._itemsCount},openPage:function(){this._grid.loadData()},loadParams:function(){var a=this._grid;return{pageIndex:a.option("pageIndex"),pageSize:a.option("pageSize")}},reset:function(){return this._grid.loadData()},sort:function(){return this._grid.loadData()},finishLoad:function(a){this._itemsCount=a.itemsCount,this._grid.option("data",a.data)},finishInsert:function(){this._grid.search()},finishDelete:function(){this._grid.search()}},a.loadStrategies={DirectLoadingStrategy:c,PageLoadingStrategy:d}}(jsGrid,jQuery),function(a){var b=function(a){return"undefined"!=typeof a&&null!==a},c={string:function(a,c){return b(a)||b(c)?b(a)?b(c)?(""+a).localeCompare(""+c):1:-1:0},number:function(a,b){return a-b},date:function(a,b){return a-b},numberAsString:function(a,b){return parseFloat(a)-parseFloat(b)}};a.sortStrategies=c}(jsGrid,jQuery),function(a,b,c){function d(a){this._init(a)}d.prototype={_init:function(a){b.extend(!0,this,a)},validate:function(a){var c=[];return b.each(this._normalizeRules(a.rules),function(d,e){if(!e.validator(a.value,a.item,e.param)){var f=b.isFunction(e.message)?e.message(a.value,a.item):e.message;c.push(f)}}),c},_normalizeRules:function(a){return b.isArray(a)||(a=[a]),b.map(a,b.proxy(function(a){return this._normalizeRule(a)},this))},_normalizeRule:function(a){if("string"==typeof a&&(a={validator:a}),b.isFunction(a)&&(a={validator:a}),!b.isPlainObject(a))throw Error("wrong validation config specified");return a=b.extend({},a),b.isFunction(a.validator)?a:this._applyNamedValidator(a,a.validator)},_applyNamedValidator:function(a,c){delete a.validator;var d=e[c];if(!d)throw Error('unknown validator "'+c+'"');return b.isFunction(d)&&(d={validator:d}),b.extend({},d,a)}},a.Validation=d;var e={required:{message:"Field is required",validator:function(a){return a!==c&&null!==a&&""!==a}},rangeLength:{message:"Field value length is out of the defined range",validator:function(a,b,c){return a.length>=c[0]&&a.length<=c[1]}},minLength:{message:"Field value is too short",validator:function(a,b,c){return a.length>=c}},maxLength:{message:"Field value is too long",validator:function(a,b,c){return a.length<=c}},pattern:{message:"Field value is not matching the defined pattern",validator:function(a,b,c){return"string"==typeof c&&(c=new RegExp("^(?:"+c+")$")),c.test(a)}},range:{message:"Field value is out of the defined range",validator:function(a,b,c){return a>=c[0]&&a<=c[1]}},min:{message:"Field value is too small",validator:function(a,b,c){return a>=c}},max:{message:"Field value is too large",validator:function(a,b,c){return c>=a}}};a.validators=e}(jsGrid,jQuery),function(a,b,c){function d(a){b.extend(!0,this,a),this.sortingFunc=this._getSortingFunc()}d.prototype={name:"",title:null,css:"",align:"",width:100,visible:!0,filtering:!0,inserting:!0,editing:!0,sorting:!0,sorter:"string",headerTemplate:function(){return this.title===c||null===this.title?this.name:this.title},itemTemplate:function(a){return a},filterTemplate:function(){return""},insertTemplate:function(){return""},editTemplate:function(a,b){return this._value=a,this.itemTemplate(a,b)},filterValue:function(){return""},insertValue:function(){return""},editValue:function(){return this._value},_getSortingFunc:function(){var c=this.sorter;if(b.isFunction(c))return c;if("string"==typeof c)return a.sortStrategies[c];throw Error('wrong sorter for the field "'+this.name+'"!')}},a.Field=d}(jsGrid,jQuery),function(a,b){function c(a){d.call(this,a)}var d=a.Field;c.prototype=new d({autosearch:!0,readOnly:!1,filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createTextBox();return this.autosearch&&b.on("keypress",function(b){13===b.which&&(a.search(),b.preventDefault())}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createTextBox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextBox();return b.val(a),b},filterValue:function(){return this.filterControl.val()},insertValue:function(){return this.insertControl.val()},editValue:function(){return this.editControl.val()},_createTextBox:function(){return b("<input>").attr("type","text").prop("readonly",!!this.readOnly)}}),a.fields.text=a.TextField=c}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.TextField;d.prototype=new e({sorter:"number",align:"right",readOnly:!1,filterValue:function(){return this.filterControl.val()?parseInt(this.filterControl.val()||0,10):c},insertValue:function(){return this.insertControl.val()?parseInt(this.insertControl.val()||0,10):c},editValue:function(){return this.editControl.val()?parseInt(this.editControl.val()||0,10):c},_createTextBox:function(){return b("<input>").attr("type","number").prop("readonly",!!this.readOnly)}}),a.fields.number=a.NumberField=d}(jsGrid,jQuery),function(a,b){function c(a){d.call(this,a)}var d=a.TextField;c.prototype=new d({insertTemplate:function(){return this.inserting?this.insertControl=this._createTextArea():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createTextArea();return b.val(a),b},_createTextArea:function(){return b("<textarea>").prop("readonly",!!this.readOnly)}}),a.fields.textarea=a.TextAreaField=c}(jsGrid,jQuery),function(a,b,c){function d(a){if(this.items=[],this.selectedIndex=-1,this.valueField="",this.textField="",a.valueField&&a.items.length){var b=a.items[0][a.valueField];this.valueType=typeof b===f?f:g}this.sorter=this.valueType,e.call(this,a)}var e=a.NumberField,f="number",g="string";d.prototype=new e({align:"center",valueType:f,itemTemplate:function(a){var d,e=this.items,f=this.valueField,g=this.textField;d=f?b.grep(e,function(b){return b[f]===a})[0]||{}:e[a];var h=g?d[g]:d;return h===c||null===h?"":h},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,b=this.filterControl=this._createSelect();return this.autosearch&&b.on("change",function(){a.search()}),b},insertTemplate:function(){return this.inserting?this.insertControl=this._createSelect():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createSelect();return a!==c&&b.val(a),b},filterValue:function(){var a=this.filterControl.val();return this.valueType===f?parseInt(a||0,10):a},insertValue:function(){var a=this.insertControl.val();return this.valueType===f?parseInt(a||0,10):a},editValue:function(){var a=this.editControl.val();return this.valueType===f?parseInt(a||0,10):a},_createSelect:function(){var a=b("<select>"),c=this.valueField,d=this.textField,e=this.selectedIndex;return b.each(this.items,function(f,g){var h=c?g[c]:f,i=d?g[d]:g,j=b("<option>").attr("value",h).text(i).appendTo(a);j.prop("selected",e===f)}),a.prop("disabled",!!this.readOnly),a}}),a.fields.select=a.SelectField=d}(jsGrid,jQuery),function(a,b,c){function d(a){e.call(this,a)}var e=a.Field;d.prototype=new e({sorter:"number",align:"center",autosearch:!0,itemTemplate:function(a){return this._createCheckbox().prop({checked:a,disabled:!0})},filterTemplate:function(){if(!this.filtering)return"";var a=this._grid,c=this.filterControl=this._createCheckbox();return c.prop({readOnly:!0,indeterminate:!0}),c.on("click",function(){var a=b(this); +a.prop("readOnly")?a.prop({checked:!1,readOnly:!1}):a.prop("checked")||a.prop({readOnly:!0,indeterminate:!0})}),this.autosearch&&c.on("click",function(){a.search()}),c},insertTemplate:function(){return this.inserting?this.insertControl=this._createCheckbox():""},editTemplate:function(a){if(!this.editing)return this.itemTemplate.apply(this,arguments);var b=this.editControl=this._createCheckbox();return b.prop("checked",a),b},filterValue:function(){return this.filterControl.get(0).indeterminate?c:this.filterControl.is(":checked")},insertValue:function(){return this.insertControl.is(":checked")},editValue:function(){return this.editControl.is(":checked")},_createCheckbox:function(){return b("<input>").attr("type","checkbox")}}),a.fields.checkbox=a.CheckboxField=d}(jsGrid,jQuery),function(a,b){function c(a){d.call(this,a),this._configInitialized=!1}var d=a.Field;c.prototype=new d({css:"jsgrid-control-field",align:"center",width:50,filtering:!1,inserting:!1,editing:!1,sorting:!1,buttonClass:"jsgrid-button",modeButtonClass:"jsgrid-mode-button",modeOnButtonClass:"jsgrid-mode-on-button",searchModeButtonClass:"jsgrid-search-mode-button",insertModeButtonClass:"jsgrid-insert-mode-button",editButtonClass:"jsgrid-edit-button",deleteButtonClass:"jsgrid-delete-button",searchButtonClass:"jsgrid-search-button",clearFilterButtonClass:"jsgrid-clear-filter-button",insertButtonClass:"jsgrid-insert-button",updateButtonClass:"jsgrid-update-button",cancelEditButtonClass:"jsgrid-cancel-edit-button",searchModeButtonTooltip:"Switch to searching",insertModeButtonTooltip:"Switch to inserting",editButtonTooltip:"Edit",deleteButtonTooltip:"Delete",searchButtonTooltip:"Search",clearFilterButtonTooltip:"Clear filter",insertButtonTooltip:"Insert",updateButtonTooltip:"Update",cancelEditButtonTooltip:"Cancel edit",editButton:!0,deleteButton:!0,clearFilterButton:!0,modeSwitchButton:!0,_initConfig:function(){this._hasFiltering=this._grid.filtering,this._hasInserting=this._grid.inserting,this._hasInserting&&this.modeSwitchButton&&(this._grid.inserting=!1),this._configInitialized=!0},headerTemplate:function(){this._configInitialized||this._initConfig();var a=this._hasFiltering,b=this._hasInserting;return this.modeSwitchButton&&(a||b)?a&&!b?this._createFilterSwitchButton():b&&!a?this._createInsertSwitchButton():this._createModeSwitchButton():""},itemTemplate:function(a,c){var d=b([]);return this.editButton&&(d=d.add(this._createEditButton(c))),this.deleteButton&&(d=d.add(this._createDeleteButton(c))),d},filterTemplate:function(){var a=this._createSearchButton();return this.clearFilterButton?a.add(this._createClearFilterButton()):a},insertTemplate:function(){return this._createInsertButton()},editTemplate:function(){return this._createUpdateButton().add(this._createCancelEditButton())},_createFilterSwitchButton:function(){return this._createOnOffSwitchButton("filtering",this.searchModeButtonClass,!0)},_createInsertSwitchButton:function(){return this._createOnOffSwitchButton("inserting",this.insertModeButtonClass,!1)},_createOnOffSwitchButton:function(a,c,d){var e=d,f=b.proxy(function(){g.toggleClass(this.modeOnButtonClass,e)},this),g=this._createGridButton(this.modeButtonClass+" "+c,"",function(b){e=!e,b.option(a,e),f()});return f(),g},_createModeSwitchButton:function(){var a=!1,c=b.proxy(function(){d.attr("title",a?this.searchModeButtonTooltip:this.insertModeButtonTooltip).toggleClass(this.insertModeButtonClass,!a).toggleClass(this.searchModeButtonClass,a)},this),d=this._createGridButton(this.modeButtonClass,"",function(b){a=!a,b.option("inserting",a),b.option("filtering",!a),c()});return c(),d},_createEditButton:function(a){return this._createGridButton(this.editButtonClass,this.editButtonTooltip,function(b,c){b.editItem(a),c.stopPropagation()})},_createDeleteButton:function(a){return this._createGridButton(this.deleteButtonClass,this.deleteButtonTooltip,function(b,c){b.deleteItem(a),c.stopPropagation()})},_createSearchButton:function(){return this._createGridButton(this.searchButtonClass,this.searchButtonTooltip,function(a){a.search()})},_createClearFilterButton:function(){return this._createGridButton(this.clearFilterButtonClass,this.clearFilterButtonTooltip,function(a){a.clearFilter()})},_createInsertButton:function(){return this._createGridButton(this.insertButtonClass,this.insertButtonTooltip,function(a){a.insertItem().done(function(){a.clearInsert()})})},_createUpdateButton:function(){return this._createGridButton(this.updateButtonClass,this.updateButtonTooltip,function(a,b){a.updateItem(),b.stopPropagation()})},_createCancelEditButton:function(){return this._createGridButton(this.cancelEditButtonClass,this.cancelEditButtonTooltip,function(a,b){a.cancelEdit(),b.stopPropagation()})},_createGridButton:function(a,c,d){var e=this._grid;return b("<input>").addClass(this.buttonClass).addClass(a).attr({type:"button",title:c}).on("click",function(a){d(e,a)})},editValue:function(){return""}}),a.fields.control=a.ControlField=c}(jsGrid,jQuery); \ No newline at end of file
3
Brought dist/ back to 1.5.3
2
.js
min
mit
tabalinas/jsgrid
10063494
<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 { public function boot() { LumenPassport::routes($this->app); /* rest of boot */ } } ``` ### User model Make sure your user model uses **Laravel Passport**'s `HasApiTokens` trait. ```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 and closed. ## 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> Update README.md <DFF> @@ -308,7 +308,9 @@ Simply run it to remove expired refresh tokens and their corresponding access to ## Error and issue resolution -Instead of opening a new issue, please see if someone has already had it and it has been resolved and closed. +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
3
Update README.md
1
.md
md
mit
dusterio/lumen-passport
10063495
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063496
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063497
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063498
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063499
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063500
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063501
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063502
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063503
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063504
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063505
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063506
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063507
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063508
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063509
<NME> VisualLineText.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 Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { /// <summary> /// VisualLineElement that represents a piece of text. /// </summary> public class VisualLineText : VisualLineElement { /// <summary> /// Gets the parent visual line. /// </summary> public VisualLine ParentVisualLine { get; } /// <summary> /// Creates a visual line text element with the specified length. /// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its /// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string. /// </summary> public VisualLineText(VisualLine parentVisualLine, int length) : base(length, length) { ParentVisualLine = parentVisualLine ?? throw new ArgumentNullException(nameof(parentVisualLine)); } /// <summary> /// Override this method to control the type of new VisualLineText instances when /// the visual line is split due to syntax highlighting. /// </summary> protected virtual VisualLineText CreateInstance(int length) { return new VisualLineText(ParentVisualLine, length); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = startVisualColumn - VisualColumn; var text = context.GetText(offset, DocumentLength - relativeOffset); return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); } /// <inheritdoc/> if (bufferOffset + text.Count > text.Text.Length) { bufferOffset = 0; } var textSlice = new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count, bufferOffset); return new TextCharacters(textSlice, TextRunProperties); } /// <inheritdoc/> public override bool IsWhitespace(int visualColumn) { var offset = visualColumn - VisualColumn + ParentVisualLine.FirstDocumentLine.Offset + RelativeTextOffset; return char.IsWhiteSpace(ParentVisualLine.Document.GetCharAt(offset)); } /// <inheritdoc/> public override ReadOnlySlice<char> GetPrecedingText(int visualColumnLimit, ITextRunConstructionContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var relativeOffset = visualColumnLimit - VisualColumn; var text = context.GetText(context.VisualLine.FirstDocumentLine.Offset + RelativeTextOffset, relativeOffset); return new ReadOnlySlice<char>(text.Text.AsMemory(), text.Offset, text.Count); } /// <inheritdoc/> public override bool CanSplit => true; /// <inheritdoc/> public override void Split(int splitVisualColumn, IList<VisualLineElement> elements, int elementIndex) { if (splitVisualColumn <= VisualColumn || splitVisualColumn >= VisualColumn + VisualLength) throw new ArgumentOutOfRangeException(nameof(splitVisualColumn), splitVisualColumn, "Value must be between " + (VisualColumn + 1) + " and " + (VisualColumn + VisualLength - 1)); if (elements == null) throw new ArgumentNullException(nameof(elements)); if (elements[elementIndex] != this) throw new ArgumentException("Invalid elementIndex - couldn't find this element at the index"); var relativeSplitPos = splitVisualColumn - VisualColumn; var splitPart = CreateInstance(DocumentLength - relativeSplitPos); SplitHelper(this, splitPart, splitVisualColumn, relativeSplitPos + RelativeTextOffset); elements.Insert(elementIndex + 1, splitPart); } /// <inheritdoc/> public override int GetRelativeOffset(int visualColumn) { return RelativeTextOffset + visualColumn - VisualColumn; } /// <inheritdoc/> public override int GetVisualColumn(int relativeTextOffset) { return VisualColumn + relativeTextOffset - RelativeTextOffset; } /// <inheritdoc/> public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { var textOffset = ParentVisualLine.StartOffset + RelativeTextOffset; var pos = TextUtilities.GetNextCaretPosition(ParentVisualLine.Document, textOffset + visualColumn - VisualColumn, direction, mode); if (pos < textOffset || pos > textOffset + DocumentLength) return -1; return VisualColumn + pos - textOffset; } } } <MSG> Fix CreateTextRun <DFF> @@ -66,7 +66,7 @@ namespace AvaloniaEdit.Rendering var text = context.GetText(offset, DocumentLength - relativeOffset); - return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory()), TextRunProperties); + return new TextCharacters(new ReadOnlySlice<char>(text.AsMemory(), offset, text.Length), TextRunProperties); } /// <inheritdoc/>
1
Fix CreateTextRun
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063510
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063511
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063512
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063513
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063514
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063515
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063516
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063517
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063518
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063519
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063520
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063521
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063522
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063523
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063524
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); Caret.PositionChanged += CaretPositionChanged; AttachTypingEvents(); LeftMargins.CollectionChanged += LeftMargins_CollectionChanged; DefaultInputHandler = new TextAreaDefaultInputHandler(this); ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var selection = _textArea.Selection; var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = selection.StartPosition.Column, CursorOffset = selection.EndPosition.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> Merge branch 'master' into fixes/visualLineLeak <DFF> @@ -1185,16 +1185,18 @@ namespace AvaloniaEdit.Editing return default; } - var selection = _textArea.Selection; + var lineIndex = _textArea.Caret.Line; - var documentLine = _textArea.Document.GetLineByNumber(selection.StartPosition.Line); + var position = _textArea.Caret.Position; + + var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { - AnchorOffset = selection.StartPosition.Column, - CursorOffset = selection.EndPosition.Column, + AnchorOffset = 0, + CursorOffset = position.Column, Text = text }; }
6
Merge branch 'master' into fixes/visualLineLeak
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063525
<NME> pl.js <BEF> ADDFILE <MSG> i18n: Add Polish localization <DFF> @@ -0,0 +1,62 @@ +(function(jsGrid) { + + jsGrid.locales.pl = { + grid: { + noDataContent: "Nie znaleziono", + deleteConfirm: "Czy jesteś pewien?", + pagerFormat: "Strony: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} z {pageCount}", + pagePrevText: "Poprzednia", + pageNextText: "Następna", + pageFirstText: "Pierwsza", + pageLastText: "Ostatnia", + loadMessage: "Proszę czekać...", + invalidMessage: "Wprowadzono nieprawidłowe dane!" + }, + + loadIndicator: { + message: "Ładowanie..." + }, + + fields: { + control: { + searchModeButtonTooltip: "Wyszukiwanie", + insertModeButtonTooltip: "Dodawanie", + editButtonTooltip: "Edytuj", + deleteButtonTooltip: "Usuń", + searchButtonTooltip: "Szukaj", + clearFilterButtonTooltip: "Wyczyść filtr", + insertButtonTooltip: "Dodaj", + updateButtonTooltip: "Aktualizuj", + cancelEditButtonTooltip: "Anuluj edytowanie" + } + }, + + validators: { + required: { + message: "Pole jest wymagane" + }, + rangeLength: { + message: "Długość wartości pola znajduje się poza zdefiniowanym zakresem" + }, + minLength: { + message: "Wartość pola jest zbyt długa" + }, + maxLength: { + message: "Wartość pola jest zbyt krótka" + }, + pattern: { + message: "Wartość pola nie zgadza się ze zdefiniowanym wzorem" + }, + range: { + message: "Wartość pola znajduje się poza zdefiniowanym zakresem" + }, + min: { + message: "Wartość pola jest zbyt duża" + }, + max: { + message: "Wartość pola jest zbyt mała" + } + } + }; + +}(jsGrid, jQuery));
62
i18n: Add Polish localization
0
.js
js
mit
tabalinas/jsgrid
10063526
<NME> pl.js <BEF> ADDFILE <MSG> i18n: Add Polish localization <DFF> @@ -0,0 +1,62 @@ +(function(jsGrid) { + + jsGrid.locales.pl = { + grid: { + noDataContent: "Nie znaleziono", + deleteConfirm: "Czy jesteś pewien?", + pagerFormat: "Strony: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} z {pageCount}", + pagePrevText: "Poprzednia", + pageNextText: "Następna", + pageFirstText: "Pierwsza", + pageLastText: "Ostatnia", + loadMessage: "Proszę czekać...", + invalidMessage: "Wprowadzono nieprawidłowe dane!" + }, + + loadIndicator: { + message: "Ładowanie..." + }, + + fields: { + control: { + searchModeButtonTooltip: "Wyszukiwanie", + insertModeButtonTooltip: "Dodawanie", + editButtonTooltip: "Edytuj", + deleteButtonTooltip: "Usuń", + searchButtonTooltip: "Szukaj", + clearFilterButtonTooltip: "Wyczyść filtr", + insertButtonTooltip: "Dodaj", + updateButtonTooltip: "Aktualizuj", + cancelEditButtonTooltip: "Anuluj edytowanie" + } + }, + + validators: { + required: { + message: "Pole jest wymagane" + }, + rangeLength: { + message: "Długość wartości pola znajduje się poza zdefiniowanym zakresem" + }, + minLength: { + message: "Wartość pola jest zbyt długa" + }, + maxLength: { + message: "Wartość pola jest zbyt krótka" + }, + pattern: { + message: "Wartość pola nie zgadza się ze zdefiniowanym wzorem" + }, + range: { + message: "Wartość pola znajduje się poza zdefiniowanym zakresem" + }, + min: { + message: "Wartość pola jest zbyt duża" + }, + max: { + message: "Wartość pola jest zbyt mała" + } + } + }; + +}(jsGrid, jQuery));
62
i18n: Add Polish localization
0
.js
js
mit
tabalinas/jsgrid
10063527
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063528
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063529
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063530
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063531
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063532
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063533
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063534
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063535
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063536
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063537
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063538
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063539
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063540
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063541
<NME> build.sh <BEF> ADDFILE <MSG> add cake bootstrap files. <DFF> @@ -0,0 +1,105 @@ +#!/usr/bin/env bash + +########################################################################## +# This is the Cake bootstrapper script for Linux and OS X. +# This file was downloaded from https://github.com/cake-build/resources +# Feel free to change this file to fit your needs. +########################################################################## + +# Define directories. +SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) +TOOLS_DIR=$SCRIPT_DIR/tools +NUGET_EXE=$TOOLS_DIR/nuget.exe +CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe +PACKAGES_CONFIG=$TOOLS_DIR/packages.config +PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum + +# Define md5sum or md5 depending on Linux/OSX +MD5_EXE= +if [[ "$(uname -s)" == "Darwin" ]]; then + MD5_EXE="md5 -r" +else + MD5_EXE="md5sum" +fi + +# Define default arguments. +SCRIPT="build.cake" +TARGET="Default" +CONFIGURATION="Release" +PLATFORM="Any CPU" +VERBOSITY="verbose" +DRYRUN= +SKIP_TESTS= +SHOW_VERSION=false +SCRIPT_ARGUMENTS=() + +# Parse arguments. +for i in "$@"; do + case $1 in + -s|--script) SCRIPT="$2"; shift ;; + -t|--target) TARGET="$2"; shift ;; + -p|--platform) PLATFORM="$2"; shift ;; + -c|--configuration) CONFIGURATION="$2"; shift ;; + --skip-tests) SKIP_TESTS="-skip-tests"; shift ;; + -v|--verbosity) VERBOSITY="$2"; shift ;; + -d|--dryrun) DRYRUN="-dryrun" ;; + --version) SHOW_VERSION=true ;; + --) shift; SCRIPT_ARGUMENTS+=("$@"); break ;; + *) SCRIPT_ARGUMENTS+=("$1") ;; + esac + shift +done + +# Make sure the tools folder exist. +if [ ! -d "$TOOLS_DIR" ]; then + mkdir "$TOOLS_DIR" +fi + +# Make sure that packages.config exist. +if [ ! -f "$TOOLS_DIR/packages.config" ]; then + echo "Downloading packages.config..." + curl -Lsfo "$TOOLS_DIR/packages.config" http://cakebuild.net/download/bootstrapper/packages + if [ $? -ne 0 ]; then + echo "An error occured while downloading packages.config." + exit 1 + fi +fi + +# Download NuGet if it does not exist. +if [ ! -f "$NUGET_EXE" ]; then + echo "Downloading NuGet..." + curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe + if [ $? -ne 0 ]; then + echo "An error occured while downloading nuget.exe." + exit 1 + fi +fi + +# Restore tools from NuGet. +pushd "$TOOLS_DIR" >/dev/null +if [ ! -f $PACKAGES_CONFIG_MD5 ] || [ "$( cat $PACKAGES_CONFIG_MD5 | sed 's/\r$//' )" != "$( $MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' )" ]; then + find . -type d ! -name . | xargs rm -rf +fi + +mono "$NUGET_EXE" install -ExcludeVersion +if [ $? -ne 0 ]; then + echo "Could not restore NuGet packages." + exit 1 +fi + +$MD5_EXE $PACKAGES_CONFIG | awk '{ print $1 }' >| $PACKAGES_CONFIG_MD5 + +popd >/dev/null + +# Make sure that Cake has been installed. +if [ ! -f "$CAKE_EXE" ]; then + echo "Could not find Cake.exe at '$CAKE_EXE'." + exit 1 +fi + +# Start Cake +if $SHOW_VERSION; then + exec mono "$CAKE_EXE" -version +else + exec mono "$CAKE_EXE" $SCRIPT -verbosity=$VERBOSITY -platform="$PLATFORM" -configuration="$CONFIGURATION" -target=$TARGET $DRYRUN $SKIP_TESTS "${SCRIPT_ARGUMENTS[@]}" +fi \ No newline at end of file
105
add cake bootstrap files.
0
.sh
sh
mit
AvaloniaUI/AvaloniaEdit
10063542
<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` ``` #### jsGrid.locale(localeName|localeConfig) Set current locale of all grids. **localeName|localeConfig** is the name of supported locale ('fr', 'es', 'pl', 'ru') or custom localization config. ```javascript // search with current grid filter $("#grid").jsGrid("search"); ``` #### jsGrid.setDefaults(config) Set default options for all grids. ```javascript ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript ``` #### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ``` ## Callbacks jsGrid allows to specify a callback function to be executed on a particular event. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid onError: function(args) {}, // on fail of any controller call onOptionChanging: function(args) {}, // before changing the grid option onOptionChanged: function(args) {}, // after changing the grid option onPageChanged: function(args) {}, // after changing the current page onRefreshing: function(args) {}, // before grid refresh onRefreshed: function(args) {}, // after grid refresh } ``` ### onDataLoading Fires before data loading. Has the following arguments: ```javascript { grid // grid instance filter // loading filter object } ``` #### Cancel Data Loading > version added: 1.2 To cancel data loading set `args.cancel = true`. In the following example loading is canceled when the filter has empty 'name' field: ```javascript $("#grid").jsGrid({ ... onDataLoading: function(args) { // cancel loading data if 'name' is empty if(args.filter.name === "") { args.cancel = true; } } }); ``` ### onDataLoaded Fires after data loading. Has the following arguments: ```javascript { grid // grid instance data // load result (array of items or data structure for loading by page scenario) } ``` In the following example the loaded data is written to the browser console. ```javascript $("#grid").jsGrid({ ... onDataLoaded: function(args) { console.log(args.data); } }); ``` ### onInit > version added: 1.5 Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: function() { ... } // called on loading finish } ``` This simple example prints messages to console instead of showing load indicator: ```javascript { loadIndicator: { show: function() { console.log("loading started"); },
3
Docs: set h3 instead of h4 for statis grid methods
3
.md
md
mit
tabalinas/jsgrid
10063543
<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` ``` #### jsGrid.locale(localeName|localeConfig) Set current locale of all grids. **localeName|localeConfig** is the name of supported locale ('fr', 'es', 'pl', 'ru') or custom localization config. ```javascript // search with current grid filter $("#grid").jsGrid("search"); ``` #### jsGrid.setDefaults(config) Set default options for all grids. ```javascript ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript ``` #### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ``` ## Callbacks jsGrid allows to specify a callback function to be executed on a particular event. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid onError: function(args) {}, // on fail of any controller call onOptionChanging: function(args) {}, // before changing the grid option onOptionChanged: function(args) {}, // after changing the grid option onPageChanged: function(args) {}, // after changing the current page onRefreshing: function(args) {}, // before grid refresh onRefreshed: function(args) {}, // after grid refresh } ``` ### onDataLoading Fires before data loading. Has the following arguments: ```javascript { grid // grid instance filter // loading filter object } ``` #### Cancel Data Loading > version added: 1.2 To cancel data loading set `args.cancel = true`. In the following example loading is canceled when the filter has empty 'name' field: ```javascript $("#grid").jsGrid({ ... onDataLoading: function(args) { // cancel loading data if 'name' is empty if(args.filter.name === "") { args.cancel = true; } } }); ``` ### onDataLoaded Fires after data loading. Has the following arguments: ```javascript { grid // grid instance data // load result (array of items or data structure for loading by page scenario) } ``` In the following example the loaded data is written to the browser console. ```javascript $("#grid").jsGrid({ ... onDataLoaded: function(args) { console.log(args.data); } }); ``` ### onInit > version added: 1.5 Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: function() { ... } // called on loading finish } ``` This simple example prints messages to console instead of showing load indicator: ```javascript { loadIndicator: { show: function() { console.log("loading started"); },
3
Docs: set h3 instead of h4 for statis grid methods
3
.md
md
mit
tabalinas/jsgrid
10063544
<NME> jsgrid.js <BEF> /* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ (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}", ITEM_COUNT_PLACEHOLDER = "{itemCount}", EMPTY_HREF = "javascript:void(0);"; return value.apply(context, $.makeArray(arguments).slice(2)); } return value; }; var normalizePromise = function(promise) { var d = $.Deferred(); if(promise && promise.then) { promise.then(function() { d.resolve.apply(d, arguments); }, function() { d.reject.apply(d, arguments); }); } else { d.resolve(promise); } return d.promise(); }; 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")); } }, rowDoubleClick: $.noop, noDataContent: "Not found", noDataRowClass: "jsgrid-nodata-row", heading: true, headerRowRenderer: null, headerRowClass: "jsgrid-header-row", headerCellClass: "jsgrid-header-cell", 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", cellClass: "jsgrid-cell", 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", pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button", pageClass: "jsgrid-pager-page", currentPageClass: "jsgrid-pager-current-page", customLoading: false, pageLoading: false, autoload: false, controller: defaultController, loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, invalidMessage: "Invalid data entered!", invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.message || null; }); window.alert([this.invalidMessage].concat(messages).join("\n")); }, onInit: $.noop, onRefreshing: $.noop, onRefreshed: $.noop, onPageChanged: $.noop, onItemDeleting: $.noop, onItemDeleted: $.noop, onItemInserting: $.noop, onItemInserted: $.noop, onItemEditing: $.noop, onItemUpdating: $.noop, onItemUpdated: $.noop, onItemInvalid: $.noop, onDataLoading: $.noop, onDataLoaded: $.noop, onOptionChanging: $.noop, onOptionChanged: $.noop, onError: $.noop, invalidClass: "jsgrid-invalid", 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(); this._callEventHandler(this.onInit) }, 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)); }, renderTemplate: function(source, context, config) { args = []; for(var key in config) { args.push(config[key]); } args.unshift(source, context); source = getOrApply.apply(null, args); return (source === undefined || source === null) ? "" : source; }, loadIndicator: function(config) { return new jsGrid.LoadIndicator(config); }, validation: function(config) { return jsGrid.Validation && new jsGrid.Validation(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); }, fieldOption: function(field, key, value) { field = this._normalizeField(field); if(arguments.length === 2) return field[key]; field[key] = value; this._renderGrid(); }, _handleOptionChange: function(name, value) { this[name] = value; switch(name) { case "width": case "height": this._refreshSize(); break; case "rowClass": case "rowRenderer": case "rowClick": case "rowDoubleClick": 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": case "pagerRenderer": 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 "loadStrategy": 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; case "updateOnResize": this._detachWindowResizeCallback(); this._attachWindowResizeCallback(); break; case "invalidNotify": case "invalidMessage": break; default: this.render(); break; } }, destroy: function() { this._detachWindowResizeCallback(); this._clear(); this._container.removeData(JSGRID_DATA_KEY); }, render: function() { this._renderGrid(); return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); }, _renderGrid: 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._validation = this._createValidation(); this.refresh(); }, _createLoadIndicator: function() { return getOrApply(this.loadIndicator, this, { message: this.loadMessage, shading: this.loadShading, container: this._container }); }, _createValidation: function() { return getOrApply(this.validation, this); }, _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) .addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "") .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) .on("scroll", $.proxy(function(e) { this._header.scrollLeft(e.target.scrollLeft); }, this)); 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) { if(field.visible) { callBack.call(self, field, index); } }); }, _createHeaderRow: function() { if($.isFunction(this.headerRowRenderer)) return $(this.renderTemplate(this.headerRowRenderer, this)); var $result = $("<tr>").addClass(this.headerRowClass); this._eachField(function(field, index) { var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass) .append(this.renderTemplate(field.headerTemplate, field)) .appendTo($result); if(this.sorting && field.sorting) { $th.addClass(this.sortableClass) .on("click", $.proxy(function() { this.sort(index); }, this)); } }); return $result; }, _prepareCell: function(cell, field, cssprop, cellClass) { return $(cell).css("width", field.width) .addClass(cellClass || this.cellClass) .addClass((cssprop && field[cssprop]) || field.css) .addClass(field.align ? ("jsgrid-align-" + field.align) : ""); }, _createFilterRow: function() { if($.isFunction(this.filterRowRenderer)) return $(this.renderTemplate(this.filterRowRenderer, this)); var $result = $("<tr>").addClass(this.filterRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "filtercss") .append(this.renderTemplate(field.filterTemplate, field)) .appendTo($result); }); return $result; }, _createInsertRow: function() { if($.isFunction(this.insertRowRenderer)) return $(this.renderTemplate(this.insertRowRenderer, this)); var $result = $("<tr>").addClass(this.insertRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "insertcss") .append(this.renderTemplate(field.insertTemplate, field)) .appendTo($result); }); return $result; }, _callEventHandler: function(handler, eventParams) { handler.call(this, $.extend(eventParams, { grid: this })); return eventParams; }, reset: function() { this._resetSorting(); this._resetPager(); return this._loadStrategy.reset(); }, _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 amountOfFields = 0; this._eachField(function() { amountOfFields++; }); return $("<tr>").addClass(this.noDataRowClass) .append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields) .append(this.renderTemplate(this.noDataContent, this))); }, _createRow: function(item, itemIndex) { var $result; if($.isFunction(this.rowRenderer)) { $result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: 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)) .on("dblclick", $.proxy(function(e) { this.rowDoubleClick({ 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 = this._getItemFieldValue(item, field); var args = { value: fieldValue, item : item }; if($.isFunction(field.cellRenderer)) { $result = this.renderTemplate(field.cellRenderer, field, args); } else { $result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args)); } return this._prepareCell($result, field); }, _getItemFieldValue: function(item, field) { var props = field.name.split('.'); var result = item[props.shift()]; while(result && props.length) { result = result[props.shift()]; } return result; }, _setItemFieldValue: function(item, field, value) { var props = field.name.split('.'); var current = item; var prop = props[0]; while(current && props.length) { item = current; prop = props.shift(); current = item[prop]; } if(!current) { while(props.length) { item = item[prop] = {}; prop = props.shift(); } } item[prop] = value; }, 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._normalizeField(field); order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC); this._sortField = field; this._sortOrder = order; }, _normalizeField: 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 = this._visibleFieldIndex(this._sortField); this._headerRow.find("th").eq(fieldIndex) .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass); }, _visibleFieldIndex: function(field) { return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; })); }, _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) { $pagerContainer.append(this._createPager()); } var showPager = this.paging && this._pagesCount() > 1; $pagerContainer.toggle(showPager); }, _createPager: function() { var $result; if($.isFunction(this.pagerRenderer)) { $result = $(this.pagerRenderer({ pageIndex: this.pageIndex, pageCount: this._pagesCount() })); } else { $result = $("<div>").append(this._createPagerByFormat()); } $result.addClass(this.pagerClass); return $result; }, _createPagerByFormat: function() { var pageIndex = this.pageIndex, pageCount = this._pagesCount(), var pageIndex = this.pageIndex, pageCount = this._pagesCount(), itemCount = this._itemsCount(), pagerParts = this.pagerFormat.split(" "); return $.map(pagerParts, $.proxy(function(pagerPart) { } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1); } else if(pagerPart === PREV_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1); } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount); } else if(pagerPart === LAST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount); } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) { result = pageIndex; } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) { result = pageCount; } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) { result = itemCount; } result = pageCount; } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) { result = itemCount; } return $.isArray(result) ? result.concat([" "]) : [result, " "]; 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, isActive) { return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass), isActive ? function() { this.openPage(pageIndex); } : $.noop); }, _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 width = (this.width === "auto") ? this._getAutoWidth() : this.width; this._container.width(width); }, _getAutoWidth: function() { var $headerGrid = this._headerGrid, $header = this._header; $headerGrid.width("auto"); var contentWidth = $headerGrid.outerWidth(); var borderWidth = $header.outerWidth() - $header.innerWidth(); $headerGrid.width(""); return contentWidth + borderWidth; }, _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; } this._callEventHandler(this.onPageChanged, { pageIndex: pageIndex }); }, _controllerCall: function(method, param, isCanceled, doneCallback) { if(isCanceled) return $.Deferred().reject().promise(); this._showLoading(); var controller = this._controller; if(!controller || !controller[method]) { throw Error("controller has no method '" + method + "'"); } return normalizePromise(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() { if(!this.loadIndication) return; clearTimeout(this._loadingTimer); this._loadingTimer = setTimeout($.proxy(function() { this._loadIndicator.show(); }, this), this.loadIndicationDelay); }, _hideLoading: function() { if(!this.loadIndication) return; 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()); var args = this._callEventHandler(this.onDataLoading, { filter: filter }); return this._controllerCall("loadData", filter, args.cancel, function(loadedData) { if(!loadedData) return; this._loadStrategy.finishLoad(loadedData); this._callEventHandler(this.onDataLoaded, { data: loadedData }); }); }, 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._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; 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: '1.5.3' }; }(window, jQuery)); (function(jsGrid, $, undefined) { function LoadIndicator(config) { this._init(config); } LoadIndicator.prototype = { container: "body", message: "Loading...", shading: true, zIndex: 1000, shaderClass: "jsgrid-load-shader", loadPanelClass: "jsgrid-load-panel", _init: function(config) { $.extend(true, this, config); this._initContainer(); this._initShader(); this._initLoadPanel(); }, _initContainer: function() { this._container = $(this.container); }, _initShader: function() { if(!this.shading) return; this._shader = $("<div>").addClass(this.shaderClass) .hide() .css({ position: "absolute", top: 0, right: 0, bottom: 0, left: 0, zIndex: this.zIndex }) .appendTo(this._container); }, _initLoadPanel: function() { this._loadPanel = $("<div>").addClass(this.loadPanelClass) .text(this.message) .hide() .css({ position: "absolute", top: "50%", left: "50%", zIndex: this.zIndex }) .appendTo(this._container); }, show: function() { var $loadPanel = this._loadPanel.show(); var actualWidth = $loadPanel.outerWidth(); var actualHeight = $loadPanel.outerHeight(); $loadPanel.css({ marginTop: -actualHeight / 2, marginLeft: -actualWidth / 2 }); this._shader.show(); }, hide: function() { this._loadPanel.hide(); this._shader.hide(); } }; jsGrid.LoadIndicator = LoadIndicator; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { function DirectLoadingStrategy(grid) { this._grid = grid; } DirectLoadingStrategy.prototype = { firstDisplayIndex: function() { var grid = this._grid; return grid.option("paging") ? (grid.option("pageIndex") - 1) * grid.option("pageSize") : 0; }, lastDisplayIndex: function() { var grid = this._grid; var itemsCount = grid.option("data").length; return grid.option("paging") ? Math.min(grid.option("pageIndex") * grid.option("pageSize"), itemsCount) : itemsCount; }, itemsCount: function() { return this._grid.option("data").length; }, openPage: function(index) { this._grid.refresh(); }, loadParams: function() { return {}; }, sort: function() { this._grid._sortData(); this._grid.refresh(); return $.Deferred().resolve().promise(); }, reset: function() { this._grid.refresh(); return $.Deferred().resolve().promise(); }, finishLoad: function(loadedData) { this._grid.option("data", loadedData); }, finishInsert: function(insertedItem) { var grid = this._grid; grid.option("data").push(insertedItem); grid.refresh(); }, finishDelete: function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.reset(); } }; function PageLoadingStrategy(grid) { this._grid = grid; this._itemsCount = 0; } PageLoadingStrategy.prototype = { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return this._grid.option("data").length; }, itemsCount: function() { return this._itemsCount; }, openPage: function(index) { this._grid.loadData(); }, loadParams: function() { var grid = this._grid; return { pageIndex: grid.option("pageIndex"), pageSize: grid.option("pageSize") }; }, reset: function() { return this._grid.loadData(); }, sort: function() { return this._grid.loadData(); }, finishLoad: function(loadedData) { this._itemsCount = loadedData.itemsCount; this._grid.option("data", loadedData.data); }, finishInsert: function(insertedItem) { this._grid.search(); }, finishDelete: function(deletedItem, deletedItemIndex) { this._grid.search(); } }; jsGrid.loadStrategies = { DirectLoadingStrategy: DirectLoadingStrategy, PageLoadingStrategy: PageLoadingStrategy }; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var isDefined = function(val) { return typeof(val) !== "undefined" && val !== null; }; var sortStrategies = { string: function(str1, str2) { if(!isDefined(str1) && !isDefined(str2)) return 0; if(!isDefined(str1)) return -1; if(!isDefined(str2)) return 1; return ("" + str1).localeCompare("" + str2); }, number: function(n1, n2) { return n1 - n2; }, date: function(dt1, dt2) { return dt1 - dt2; }, numberAsString: function(n1, n2) { return parseFloat(n1) - parseFloat(n2); } }; jsGrid.sortStrategies = sortStrategies; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { function Validation(config) { this._init(config); } Validation.prototype = { _init: function(config) { $.extend(true, this, config); }, validate: function(args) { var errors = []; $.each(this._normalizeRules(args.rules), function(_, rule) { if(rule.validator(args.value, args.item, rule.param)) return; var errorMessage = $.isFunction(rule.message) ? rule.message(args.value, args.item) : rule.message; errors.push(errorMessage); }); return errors; }, _normalizeRules: function(rules) { if(!$.isArray(rules)) rules = [rules]; return $.map(rules, $.proxy(function(rule) { return this._normalizeRule(rule); }, this)); }, _normalizeRule: function(rule) { if(typeof rule === "string") rule = { validator: rule }; if($.isFunction(rule)) rule = { validator: rule }; if($.isPlainObject(rule)) rule = $.extend({}, rule); else throw Error("wrong validation config specified"); if($.isFunction(rule.validator)) return rule; return this._applyNamedValidator(rule, rule.validator); }, _applyNamedValidator: function(rule, validatorName) { delete rule.validator; var validator = validators[validatorName]; if(!validator) throw Error("unknown validator \"" + validatorName + "\""); if($.isFunction(validator)) { validator = { validator: validator }; } return $.extend({}, validator, rule); } }; jsGrid.Validation = Validation; var validators = { required: { message: "Field is required", validator: function(value) { return value !== undefined && value !== null && value !== ""; } }, rangeLength: { message: "Field value length is out of the defined range", validator: function(value, _, param) { return value.length >= param[0] && value.length <= param[1]; } }, minLength: { message: "Field value is too short", validator: function(value, _, param) { return value.length >= param; } }, maxLength: { message: "Field value is too long", validator: function(value, _, param) { return value.length <= param; } }, pattern: { message: "Field value is not matching the defined pattern", validator: function(value, _, param) { if(typeof param === "string") { param = new RegExp("^(?:" + param + ")$"); } return param.test(value); } }, range: { message: "Field value is out of the defined range", validator: function(value, _, param) { return value >= param[0] && value <= param[1]; } }, min: { message: "Field value is too small", validator: function(value, _, param) { return value >= param; } }, max: { message: "Field value is too large", validator: function(value, _, param) { return value <= param; } } }; jsGrid.validators = validators; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { function Field(config) { $.extend(true, this, config); this.sortingFunc = this._getSortingFunc(); } Field.prototype = { name: "", title: null, css: "", align: "", width: 100, visible: true, filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", // name of SortStrategy or function to compare elements headerTemplate: function() { return (this.title === undefined || this.title === null) ? this.name : this.title; }, itemTemplate: function(value, item) { return value; }, filterTemplate: function() { return ""; }, insertTemplate: function() { return ""; }, editTemplate: function(value, item) { this._value = value; return this.itemTemplate(value, item); }, filterValue: function() { return ""; }, insertValue: function() { return ""; }, editValue: function() { return this._value; }, _getSortingFunc: function() { var sorter = this.sorter; if($.isFunction(sorter)) { return sorter; } if(typeof sorter === "string") { return jsGrid.sortStrategies[sorter]; } throw Error("wrong sorter for the field \"" + this.name + "\"!"); } }; jsGrid.Field = Field; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var Field = jsGrid.Field; function TextField(config) { Field.call(this, config); } TextField.prototype = new Field({ autosearch: true, readOnly: false, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createTextBox(); if(this.autosearch) { $result.on("keypress", function(e) { if(e.which === 13) { grid.search(); e.preventDefault(); } }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createTextBox(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createTextBox(); $result.val(value); return $result; }, filterValue: function() { return this.filterControl.val(); }, insertValue: function() { return this.insertControl.val(); }, editValue: function() { return this.editControl.val(); }, _createTextBox: function() { return $("<input>").attr("type", "text") .prop("readonly", !!this.readOnly); } }); jsGrid.fields.text = jsGrid.TextField = TextField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var TextField = jsGrid.TextField; function NumberField(config) { TextField.call(this, config); } NumberField.prototype = new TextField({ sorter: "number", align: "right", readOnly: false, filterValue: function() { return this.filterControl.val() ? parseInt(this.filterControl.val() || 0, 10) : undefined; }, insertValue: function() { return this.insertControl.val() ? parseInt(this.insertControl.val() || 0, 10) : undefined; }, editValue: function() { return this.editControl.val() ? parseInt(this.editControl.val() || 0, 10) : undefined; }, _createTextBox: function() { return $("<input>").attr("type", "number") .prop("readonly", !!this.readOnly); } }); jsGrid.fields.number = jsGrid.NumberField = NumberField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var TextField = jsGrid.TextField; function TextAreaField(config) { TextField.call(this, config); } TextAreaField.prototype = new TextField({ insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createTextArea(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createTextArea(); $result.val(value); return $result; }, _createTextArea: function() { return $("<textarea>").prop("readonly", !!this.readOnly); } }); jsGrid.fields.textarea = jsGrid.TextAreaField = TextAreaField; }(jsGrid, jQuery)); (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)); (function(jsGrid, $, undefined) { var Field = jsGrid.Field; function CheckboxField(config) { Field.call(this, config); } CheckboxField.prototype = new Field({ sorter: "number", align: "center", autosearch: true, itemTemplate: function(value) { return this._createCheckbox().prop({ checked: value, disabled: true }); }, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createCheckbox(); $result.prop({ readOnly: true, indeterminate: true }); $result.on("click", function() { var $cb = $(this); if($cb.prop("readOnly")) { $cb.prop({ checked: false, readOnly: false }); } else if(!$cb.prop("checked")) { $cb.prop({ readOnly: true, indeterminate: true }); } }); if(this.autosearch) { $result.on("click", function() { grid.search(); }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createCheckbox(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createCheckbox(); $result.prop("checked", value); return $result; }, filterValue: function() { return this.filterControl.get(0).indeterminate ? undefined : this.filterControl.is(":checked"); }, insertValue: function() { return this.insertControl.is(":checked"); }, editValue: function() { return this.editControl.is(":checked"); }, _createCheckbox: function() { return $("<input>").attr("type", "checkbox"); } }); jsGrid.fields.checkbox = jsGrid.CheckboxField = CheckboxField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var Field = jsGrid.Field; function ControlField(config) { Field.call(this, config); this._configInitialized = false; } ControlField.prototype = new Field({ css: "jsgrid-control-field", align: "center", width: 50, filtering: false, inserting: false, editing: false, sorting: false, buttonClass: "jsgrid-button", modeButtonClass: "jsgrid-mode-button", modeOnButtonClass: "jsgrid-mode-on-button", searchModeButtonClass: "jsgrid-search-mode-button", insertModeButtonClass: "jsgrid-insert-mode-button", editButtonClass: "jsgrid-edit-button", deleteButtonClass: "jsgrid-delete-button", searchButtonClass: "jsgrid-search-button", clearFilterButtonClass: "jsgrid-clear-filter-button", insertButtonClass: "jsgrid-insert-button", updateButtonClass: "jsgrid-update-button", cancelEditButtonClass: "jsgrid-cancel-edit-button", searchModeButtonTooltip: "Switch to searching", insertModeButtonTooltip: "Switch to inserting", editButtonTooltip: "Edit", deleteButtonTooltip: "Delete", searchButtonTooltip: "Search", clearFilterButtonTooltip: "Clear filter", insertButtonTooltip: "Insert", updateButtonTooltip: "Update", cancelEditButtonTooltip: "Cancel edit", editButton: true, deleteButton: true, clearFilterButton: true, modeSwitchButton: true, _initConfig: function() { this._hasFiltering = this._grid.filtering; this._hasInserting = this._grid.inserting; if(this._hasInserting && this.modeSwitchButton) { this._grid.inserting = false; } this._configInitialized = true; }, headerTemplate: function() { if(!this._configInitialized) { this._initConfig(); } var hasFiltering = this._hasFiltering; var hasInserting = this._hasInserting; if(!this.modeSwitchButton || (!hasFiltering && !hasInserting)) return ""; if(hasFiltering && !hasInserting) return this._createFilterSwitchButton(); if(hasInserting && !hasFiltering) return this._createInsertSwitchButton(); return this._createModeSwitchButton(); }, itemTemplate: function(value, item) { var $result = $([]); if(this.editButton) { $result = $result.add(this._createEditButton(item)); } if(this.deleteButton) { $result = $result.add(this._createDeleteButton(item)); } return $result; }, filterTemplate: function() { var $result = this._createSearchButton(); return this.clearFilterButton ? $result.add(this._createClearFilterButton()) : $result; }, insertTemplate: function() { return this._createInsertButton(); }, editTemplate: function() { return this._createUpdateButton().add(this._createCancelEditButton()); }, _createFilterSwitchButton: function() { return this._createOnOffSwitchButton("filtering", this.searchModeButtonClass, true); }, _createInsertSwitchButton: function() { return this._createOnOffSwitchButton("inserting", this.insertModeButtonClass, false); }, _createOnOffSwitchButton: function(option, cssClass, isOnInitially) { var isOn = isOnInitially; var updateButtonState = $.proxy(function() { $button.toggleClass(this.modeOnButtonClass, isOn); }, this); var $button = this._createGridButton(this.modeButtonClass + " " + cssClass, "", function(grid) { isOn = !isOn; grid.option(option, isOn); updateButtonState(); }); updateButtonState(); return $button; }, _createModeSwitchButton: function() { var isInserting = false; var updateButtonState = $.proxy(function() { $button.attr("title", isInserting ? this.searchModeButtonTooltip : this.insertModeButtonTooltip) .toggleClass(this.insertModeButtonClass, !isInserting) .toggleClass(this.searchModeButtonClass, isInserting); }, this); var $button = this._createGridButton(this.modeButtonClass, "", function(grid) { isInserting = !isInserting; grid.option("inserting", isInserting); grid.option("filtering", !isInserting); updateButtonState(); }); updateButtonState(); return $button; }, _createEditButton: function(item) { return this._createGridButton(this.editButtonClass, this.editButtonTooltip, function(grid, e) { grid.editItem(item); e.stopPropagation(); }); }, _createDeleteButton: function(item) { return this._createGridButton(this.deleteButtonClass, this.deleteButtonTooltip, function(grid, e) { grid.deleteItem(item); e.stopPropagation(); }); }, _createSearchButton: function() { return this._createGridButton(this.searchButtonClass, this.searchButtonTooltip, function(grid) { grid.search(); }); }, _createClearFilterButton: function() { return this._createGridButton(this.clearFilterButtonClass, this.clearFilterButtonTooltip, function(grid) { grid.clearFilter(); }); }, _createInsertButton: function() { return this._createGridButton(this.insertButtonClass, this.insertButtonTooltip, function(grid) { grid.insertItem().done(function() { grid.clearInsert(); }); }); }, _createUpdateButton: function() { return this._createGridButton(this.updateButtonClass, this.updateButtonTooltip, function(grid, e) { grid.updateItem(); e.stopPropagation(); }); }, _createCancelEditButton: function() { return this._createGridButton(this.cancelEditButtonClass, this.cancelEditButtonTooltip, function(grid, e) { grid.cancelEdit(); e.stopPropagation(); }); }, _createGridButton: function(cls, tooltip, clickHandler) { var grid = this._grid; return $("<input>").addClass(this.buttonClass) .addClass(cls) .attr({ type: "button", title: tooltip }) .on("click", function(e) { clickHandler(grid, e); }); }, editValue: function() { return ""; } }); jsGrid.fields.control = jsGrid.ControlField = ControlField; }(jsGrid, jQuery)); <MSG> Merge branch 'master' of https://github.com/tabalinas/jsgrid <DFF> @@ -22,6 +22,8 @@ PAGE_INDEX_PLACEHOLDER = "{pageIndex}", PAGE_COUNT_PLACEHOLDER = "{pageCount}", ITEM_COUNT_PLACEHOLDER = "{itemCount}", + ITEM_INDEX_FROM_PLACEHOLDER = "{itemIndexFrom}", + ITEM_INDEX_TO_PLACEHOLDER = "{itemIndexTo}", EMPTY_HREF = "javascript:void(0);"; @@ -821,6 +823,8 @@ var pageIndex = this.pageIndex, pageCount = this._pagesCount(), itemCount = this._itemsCount(), + itemIndexFrom = ((this.pageIndex - 1) * this.pageSize + 1), + itemIndexTo = Math.min((this.pageIndex * this.pageSize), itemCount), pagerParts = this.pagerFormat.split(" "); return $.map(pagerParts, $.proxy(function(pagerPart) { @@ -842,6 +846,10 @@ result = pageCount; } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) { result = itemCount; + } else if (pagerPart === ITEM_INDEX_FROM_PLACEHOLDER) { + result = itemIndexFrom; + } else if (pagerPart === ITEM_INDEX_TO_PLACEHOLDER) { + result = itemIndexTo; } return $.isArray(result) ? result.concat([" "]) : [result, " "];
8
Merge branch 'master' of https://github.com/tabalinas/jsgrid
0
.js
js
mit
tabalinas/jsgrid
10063545
<NME> jsgrid.js <BEF> /* * jsGrid v1.5.3 (http://js-grid.com) * (c) 2016 Artem Tabalin * Licensed under MIT (https://github.com/tabalinas/jsgrid/blob/master/LICENSE) */ (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}", ITEM_COUNT_PLACEHOLDER = "{itemCount}", EMPTY_HREF = "javascript:void(0);"; return value.apply(context, $.makeArray(arguments).slice(2)); } return value; }; var normalizePromise = function(promise) { var d = $.Deferred(); if(promise && promise.then) { promise.then(function() { d.resolve.apply(d, arguments); }, function() { d.reject.apply(d, arguments); }); } else { d.resolve(promise); } return d.promise(); }; 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")); } }, rowDoubleClick: $.noop, noDataContent: "Not found", noDataRowClass: "jsgrid-nodata-row", heading: true, headerRowRenderer: null, headerRowClass: "jsgrid-header-row", headerCellClass: "jsgrid-header-cell", 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", cellClass: "jsgrid-cell", 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", pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button", pageClass: "jsgrid-pager-page", currentPageClass: "jsgrid-pager-current-page", customLoading: false, pageLoading: false, autoload: false, controller: defaultController, loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, invalidMessage: "Invalid data entered!", invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.message || null; }); window.alert([this.invalidMessage].concat(messages).join("\n")); }, onInit: $.noop, onRefreshing: $.noop, onRefreshed: $.noop, onPageChanged: $.noop, onItemDeleting: $.noop, onItemDeleted: $.noop, onItemInserting: $.noop, onItemInserted: $.noop, onItemEditing: $.noop, onItemUpdating: $.noop, onItemUpdated: $.noop, onItemInvalid: $.noop, onDataLoading: $.noop, onDataLoaded: $.noop, onOptionChanging: $.noop, onOptionChanged: $.noop, onError: $.noop, invalidClass: "jsgrid-invalid", 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(); this._callEventHandler(this.onInit) }, 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)); }, renderTemplate: function(source, context, config) { args = []; for(var key in config) { args.push(config[key]); } args.unshift(source, context); source = getOrApply.apply(null, args); return (source === undefined || source === null) ? "" : source; }, loadIndicator: function(config) { return new jsGrid.LoadIndicator(config); }, validation: function(config) { return jsGrid.Validation && new jsGrid.Validation(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); }, fieldOption: function(field, key, value) { field = this._normalizeField(field); if(arguments.length === 2) return field[key]; field[key] = value; this._renderGrid(); }, _handleOptionChange: function(name, value) { this[name] = value; switch(name) { case "width": case "height": this._refreshSize(); break; case "rowClass": case "rowRenderer": case "rowClick": case "rowDoubleClick": 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": case "pagerRenderer": 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 "loadStrategy": 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; case "updateOnResize": this._detachWindowResizeCallback(); this._attachWindowResizeCallback(); break; case "invalidNotify": case "invalidMessage": break; default: this.render(); break; } }, destroy: function() { this._detachWindowResizeCallback(); this._clear(); this._container.removeData(JSGRID_DATA_KEY); }, render: function() { this._renderGrid(); return this.autoload ? this.loadData() : $.Deferred().resolve().promise(); }, _renderGrid: 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._validation = this._createValidation(); this.refresh(); }, _createLoadIndicator: function() { return getOrApply(this.loadIndicator, this, { message: this.loadMessage, shading: this.loadShading, container: this._container }); }, _createValidation: function() { return getOrApply(this.validation, this); }, _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) .addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "") .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) .on("scroll", $.proxy(function(e) { this._header.scrollLeft(e.target.scrollLeft); }, this)); 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) { if(field.visible) { callBack.call(self, field, index); } }); }, _createHeaderRow: function() { if($.isFunction(this.headerRowRenderer)) return $(this.renderTemplate(this.headerRowRenderer, this)); var $result = $("<tr>").addClass(this.headerRowClass); this._eachField(function(field, index) { var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass) .append(this.renderTemplate(field.headerTemplate, field)) .appendTo($result); if(this.sorting && field.sorting) { $th.addClass(this.sortableClass) .on("click", $.proxy(function() { this.sort(index); }, this)); } }); return $result; }, _prepareCell: function(cell, field, cssprop, cellClass) { return $(cell).css("width", field.width) .addClass(cellClass || this.cellClass) .addClass((cssprop && field[cssprop]) || field.css) .addClass(field.align ? ("jsgrid-align-" + field.align) : ""); }, _createFilterRow: function() { if($.isFunction(this.filterRowRenderer)) return $(this.renderTemplate(this.filterRowRenderer, this)); var $result = $("<tr>").addClass(this.filterRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "filtercss") .append(this.renderTemplate(field.filterTemplate, field)) .appendTo($result); }); return $result; }, _createInsertRow: function() { if($.isFunction(this.insertRowRenderer)) return $(this.renderTemplate(this.insertRowRenderer, this)); var $result = $("<tr>").addClass(this.insertRowClass); this._eachField(function(field) { this._prepareCell("<td>", field, "insertcss") .append(this.renderTemplate(field.insertTemplate, field)) .appendTo($result); }); return $result; }, _callEventHandler: function(handler, eventParams) { handler.call(this, $.extend(eventParams, { grid: this })); return eventParams; }, reset: function() { this._resetSorting(); this._resetPager(); return this._loadStrategy.reset(); }, _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 amountOfFields = 0; this._eachField(function() { amountOfFields++; }); return $("<tr>").addClass(this.noDataRowClass) .append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields) .append(this.renderTemplate(this.noDataContent, this))); }, _createRow: function(item, itemIndex) { var $result; if($.isFunction(this.rowRenderer)) { $result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: 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)) .on("dblclick", $.proxy(function(e) { this.rowDoubleClick({ 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 = this._getItemFieldValue(item, field); var args = { value: fieldValue, item : item }; if($.isFunction(field.cellRenderer)) { $result = this.renderTemplate(field.cellRenderer, field, args); } else { $result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args)); } return this._prepareCell($result, field); }, _getItemFieldValue: function(item, field) { var props = field.name.split('.'); var result = item[props.shift()]; while(result && props.length) { result = result[props.shift()]; } return result; }, _setItemFieldValue: function(item, field, value) { var props = field.name.split('.'); var current = item; var prop = props[0]; while(current && props.length) { item = current; prop = props.shift(); current = item[prop]; } if(!current) { while(props.length) { item = item[prop] = {}; prop = props.shift(); } } item[prop] = value; }, 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._normalizeField(field); order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC); this._sortField = field; this._sortOrder = order; }, _normalizeField: 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 = this._visibleFieldIndex(this._sortField); this._headerRow.find("th").eq(fieldIndex) .addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass); }, _visibleFieldIndex: function(field) { return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; })); }, _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) { $pagerContainer.append(this._createPager()); } var showPager = this.paging && this._pagesCount() > 1; $pagerContainer.toggle(showPager); }, _createPager: function() { var $result; if($.isFunction(this.pagerRenderer)) { $result = $(this.pagerRenderer({ pageIndex: this.pageIndex, pageCount: this._pagesCount() })); } else { $result = $("<div>").append(this._createPagerByFormat()); } $result.addClass(this.pagerClass); return $result; }, _createPagerByFormat: function() { var pageIndex = this.pageIndex, pageCount = this._pagesCount(), var pageIndex = this.pageIndex, pageCount = this._pagesCount(), itemCount = this._itemsCount(), pagerParts = this.pagerFormat.split(" "); return $.map(pagerParts, $.proxy(function(pagerPart) { } else if(pagerPart === FIRST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1); } else if(pagerPart === PREV_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1); } else if(pagerPart === NEXT_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount); } else if(pagerPart === LAST_PAGE_PLACEHOLDER) { result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount); } else if(pagerPart === PAGE_INDEX_PLACEHOLDER) { result = pageIndex; } else if(pagerPart === PAGE_COUNT_PLACEHOLDER) { result = pageCount; } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) { result = itemCount; } result = pageCount; } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) { result = itemCount; } return $.isArray(result) ? result.concat([" "]) : [result, " "]; 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, isActive) { return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass), isActive ? function() { this.openPage(pageIndex); } : $.noop); }, _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 width = (this.width === "auto") ? this._getAutoWidth() : this.width; this._container.width(width); }, _getAutoWidth: function() { var $headerGrid = this._headerGrid, $header = this._header; $headerGrid.width("auto"); var contentWidth = $headerGrid.outerWidth(); var borderWidth = $header.outerWidth() - $header.innerWidth(); $headerGrid.width(""); return contentWidth + borderWidth; }, _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; } this._callEventHandler(this.onPageChanged, { pageIndex: pageIndex }); }, _controllerCall: function(method, param, isCanceled, doneCallback) { if(isCanceled) return $.Deferred().reject().promise(); this._showLoading(); var controller = this._controller; if(!controller || !controller[method]) { throw Error("controller has no method '" + method + "'"); } return normalizePromise(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() { if(!this.loadIndication) return; clearTimeout(this._loadingTimer); this._loadingTimer = setTimeout($.proxy(function() { this._loadIndicator.show(); }, this), this.loadIndicationDelay); }, _hideLoading: function() { if(!this.loadIndication) return; 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()); var args = this._callEventHandler(this.onDataLoading, { filter: filter }); return this._controllerCall("loadData", filter, args.cancel, function(loadedData) { if(!loadedData) return; this._loadStrategy.finishLoad(loadedData); this._callEventHandler(this.onDataLoaded, { data: loadedData }); }); }, 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._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; 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: '1.5.3' }; }(window, jQuery)); (function(jsGrid, $, undefined) { function LoadIndicator(config) { this._init(config); } LoadIndicator.prototype = { container: "body", message: "Loading...", shading: true, zIndex: 1000, shaderClass: "jsgrid-load-shader", loadPanelClass: "jsgrid-load-panel", _init: function(config) { $.extend(true, this, config); this._initContainer(); this._initShader(); this._initLoadPanel(); }, _initContainer: function() { this._container = $(this.container); }, _initShader: function() { if(!this.shading) return; this._shader = $("<div>").addClass(this.shaderClass) .hide() .css({ position: "absolute", top: 0, right: 0, bottom: 0, left: 0, zIndex: this.zIndex }) .appendTo(this._container); }, _initLoadPanel: function() { this._loadPanel = $("<div>").addClass(this.loadPanelClass) .text(this.message) .hide() .css({ position: "absolute", top: "50%", left: "50%", zIndex: this.zIndex }) .appendTo(this._container); }, show: function() { var $loadPanel = this._loadPanel.show(); var actualWidth = $loadPanel.outerWidth(); var actualHeight = $loadPanel.outerHeight(); $loadPanel.css({ marginTop: -actualHeight / 2, marginLeft: -actualWidth / 2 }); this._shader.show(); }, hide: function() { this._loadPanel.hide(); this._shader.hide(); } }; jsGrid.LoadIndicator = LoadIndicator; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { function DirectLoadingStrategy(grid) { this._grid = grid; } DirectLoadingStrategy.prototype = { firstDisplayIndex: function() { var grid = this._grid; return grid.option("paging") ? (grid.option("pageIndex") - 1) * grid.option("pageSize") : 0; }, lastDisplayIndex: function() { var grid = this._grid; var itemsCount = grid.option("data").length; return grid.option("paging") ? Math.min(grid.option("pageIndex") * grid.option("pageSize"), itemsCount) : itemsCount; }, itemsCount: function() { return this._grid.option("data").length; }, openPage: function(index) { this._grid.refresh(); }, loadParams: function() { return {}; }, sort: function() { this._grid._sortData(); this._grid.refresh(); return $.Deferred().resolve().promise(); }, reset: function() { this._grid.refresh(); return $.Deferred().resolve().promise(); }, finishLoad: function(loadedData) { this._grid.option("data", loadedData); }, finishInsert: function(insertedItem) { var grid = this._grid; grid.option("data").push(insertedItem); grid.refresh(); }, finishDelete: function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.reset(); } }; function PageLoadingStrategy(grid) { this._grid = grid; this._itemsCount = 0; } PageLoadingStrategy.prototype = { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return this._grid.option("data").length; }, itemsCount: function() { return this._itemsCount; }, openPage: function(index) { this._grid.loadData(); }, loadParams: function() { var grid = this._grid; return { pageIndex: grid.option("pageIndex"), pageSize: grid.option("pageSize") }; }, reset: function() { return this._grid.loadData(); }, sort: function() { return this._grid.loadData(); }, finishLoad: function(loadedData) { this._itemsCount = loadedData.itemsCount; this._grid.option("data", loadedData.data); }, finishInsert: function(insertedItem) { this._grid.search(); }, finishDelete: function(deletedItem, deletedItemIndex) { this._grid.search(); } }; jsGrid.loadStrategies = { DirectLoadingStrategy: DirectLoadingStrategy, PageLoadingStrategy: PageLoadingStrategy }; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var isDefined = function(val) { return typeof(val) !== "undefined" && val !== null; }; var sortStrategies = { string: function(str1, str2) { if(!isDefined(str1) && !isDefined(str2)) return 0; if(!isDefined(str1)) return -1; if(!isDefined(str2)) return 1; return ("" + str1).localeCompare("" + str2); }, number: function(n1, n2) { return n1 - n2; }, date: function(dt1, dt2) { return dt1 - dt2; }, numberAsString: function(n1, n2) { return parseFloat(n1) - parseFloat(n2); } }; jsGrid.sortStrategies = sortStrategies; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { function Validation(config) { this._init(config); } Validation.prototype = { _init: function(config) { $.extend(true, this, config); }, validate: function(args) { var errors = []; $.each(this._normalizeRules(args.rules), function(_, rule) { if(rule.validator(args.value, args.item, rule.param)) return; var errorMessage = $.isFunction(rule.message) ? rule.message(args.value, args.item) : rule.message; errors.push(errorMessage); }); return errors; }, _normalizeRules: function(rules) { if(!$.isArray(rules)) rules = [rules]; return $.map(rules, $.proxy(function(rule) { return this._normalizeRule(rule); }, this)); }, _normalizeRule: function(rule) { if(typeof rule === "string") rule = { validator: rule }; if($.isFunction(rule)) rule = { validator: rule }; if($.isPlainObject(rule)) rule = $.extend({}, rule); else throw Error("wrong validation config specified"); if($.isFunction(rule.validator)) return rule; return this._applyNamedValidator(rule, rule.validator); }, _applyNamedValidator: function(rule, validatorName) { delete rule.validator; var validator = validators[validatorName]; if(!validator) throw Error("unknown validator \"" + validatorName + "\""); if($.isFunction(validator)) { validator = { validator: validator }; } return $.extend({}, validator, rule); } }; jsGrid.Validation = Validation; var validators = { required: { message: "Field is required", validator: function(value) { return value !== undefined && value !== null && value !== ""; } }, rangeLength: { message: "Field value length is out of the defined range", validator: function(value, _, param) { return value.length >= param[0] && value.length <= param[1]; } }, minLength: { message: "Field value is too short", validator: function(value, _, param) { return value.length >= param; } }, maxLength: { message: "Field value is too long", validator: function(value, _, param) { return value.length <= param; } }, pattern: { message: "Field value is not matching the defined pattern", validator: function(value, _, param) { if(typeof param === "string") { param = new RegExp("^(?:" + param + ")$"); } return param.test(value); } }, range: { message: "Field value is out of the defined range", validator: function(value, _, param) { return value >= param[0] && value <= param[1]; } }, min: { message: "Field value is too small", validator: function(value, _, param) { return value >= param; } }, max: { message: "Field value is too large", validator: function(value, _, param) { return value <= param; } } }; jsGrid.validators = validators; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { function Field(config) { $.extend(true, this, config); this.sortingFunc = this._getSortingFunc(); } Field.prototype = { name: "", title: null, css: "", align: "", width: 100, visible: true, filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", // name of SortStrategy or function to compare elements headerTemplate: function() { return (this.title === undefined || this.title === null) ? this.name : this.title; }, itemTemplate: function(value, item) { return value; }, filterTemplate: function() { return ""; }, insertTemplate: function() { return ""; }, editTemplate: function(value, item) { this._value = value; return this.itemTemplate(value, item); }, filterValue: function() { return ""; }, insertValue: function() { return ""; }, editValue: function() { return this._value; }, _getSortingFunc: function() { var sorter = this.sorter; if($.isFunction(sorter)) { return sorter; } if(typeof sorter === "string") { return jsGrid.sortStrategies[sorter]; } throw Error("wrong sorter for the field \"" + this.name + "\"!"); } }; jsGrid.Field = Field; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var Field = jsGrid.Field; function TextField(config) { Field.call(this, config); } TextField.prototype = new Field({ autosearch: true, readOnly: false, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createTextBox(); if(this.autosearch) { $result.on("keypress", function(e) { if(e.which === 13) { grid.search(); e.preventDefault(); } }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createTextBox(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createTextBox(); $result.val(value); return $result; }, filterValue: function() { return this.filterControl.val(); }, insertValue: function() { return this.insertControl.val(); }, editValue: function() { return this.editControl.val(); }, _createTextBox: function() { return $("<input>").attr("type", "text") .prop("readonly", !!this.readOnly); } }); jsGrid.fields.text = jsGrid.TextField = TextField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var TextField = jsGrid.TextField; function NumberField(config) { TextField.call(this, config); } NumberField.prototype = new TextField({ sorter: "number", align: "right", readOnly: false, filterValue: function() { return this.filterControl.val() ? parseInt(this.filterControl.val() || 0, 10) : undefined; }, insertValue: function() { return this.insertControl.val() ? parseInt(this.insertControl.val() || 0, 10) : undefined; }, editValue: function() { return this.editControl.val() ? parseInt(this.editControl.val() || 0, 10) : undefined; }, _createTextBox: function() { return $("<input>").attr("type", "number") .prop("readonly", !!this.readOnly); } }); jsGrid.fields.number = jsGrid.NumberField = NumberField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var TextField = jsGrid.TextField; function TextAreaField(config) { TextField.call(this, config); } TextAreaField.prototype = new TextField({ insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createTextArea(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createTextArea(); $result.val(value); return $result; }, _createTextArea: function() { return $("<textarea>").prop("readonly", !!this.readOnly); } }); jsGrid.fields.textarea = jsGrid.TextAreaField = TextAreaField; }(jsGrid, jQuery)); (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)); (function(jsGrid, $, undefined) { var Field = jsGrid.Field; function CheckboxField(config) { Field.call(this, config); } CheckboxField.prototype = new Field({ sorter: "number", align: "center", autosearch: true, itemTemplate: function(value) { return this._createCheckbox().prop({ checked: value, disabled: true }); }, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createCheckbox(); $result.prop({ readOnly: true, indeterminate: true }); $result.on("click", function() { var $cb = $(this); if($cb.prop("readOnly")) { $cb.prop({ checked: false, readOnly: false }); } else if(!$cb.prop("checked")) { $cb.prop({ readOnly: true, indeterminate: true }); } }); if(this.autosearch) { $result.on("click", function() { grid.search(); }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createCheckbox(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createCheckbox(); $result.prop("checked", value); return $result; }, filterValue: function() { return this.filterControl.get(0).indeterminate ? undefined : this.filterControl.is(":checked"); }, insertValue: function() { return this.insertControl.is(":checked"); }, editValue: function() { return this.editControl.is(":checked"); }, _createCheckbox: function() { return $("<input>").attr("type", "checkbox"); } }); jsGrid.fields.checkbox = jsGrid.CheckboxField = CheckboxField; }(jsGrid, jQuery)); (function(jsGrid, $, undefined) { var Field = jsGrid.Field; function ControlField(config) { Field.call(this, config); this._configInitialized = false; } ControlField.prototype = new Field({ css: "jsgrid-control-field", align: "center", width: 50, filtering: false, inserting: false, editing: false, sorting: false, buttonClass: "jsgrid-button", modeButtonClass: "jsgrid-mode-button", modeOnButtonClass: "jsgrid-mode-on-button", searchModeButtonClass: "jsgrid-search-mode-button", insertModeButtonClass: "jsgrid-insert-mode-button", editButtonClass: "jsgrid-edit-button", deleteButtonClass: "jsgrid-delete-button", searchButtonClass: "jsgrid-search-button", clearFilterButtonClass: "jsgrid-clear-filter-button", insertButtonClass: "jsgrid-insert-button", updateButtonClass: "jsgrid-update-button", cancelEditButtonClass: "jsgrid-cancel-edit-button", searchModeButtonTooltip: "Switch to searching", insertModeButtonTooltip: "Switch to inserting", editButtonTooltip: "Edit", deleteButtonTooltip: "Delete", searchButtonTooltip: "Search", clearFilterButtonTooltip: "Clear filter", insertButtonTooltip: "Insert", updateButtonTooltip: "Update", cancelEditButtonTooltip: "Cancel edit", editButton: true, deleteButton: true, clearFilterButton: true, modeSwitchButton: true, _initConfig: function() { this._hasFiltering = this._grid.filtering; this._hasInserting = this._grid.inserting; if(this._hasInserting && this.modeSwitchButton) { this._grid.inserting = false; } this._configInitialized = true; }, headerTemplate: function() { if(!this._configInitialized) { this._initConfig(); } var hasFiltering = this._hasFiltering; var hasInserting = this._hasInserting; if(!this.modeSwitchButton || (!hasFiltering && !hasInserting)) return ""; if(hasFiltering && !hasInserting) return this._createFilterSwitchButton(); if(hasInserting && !hasFiltering) return this._createInsertSwitchButton(); return this._createModeSwitchButton(); }, itemTemplate: function(value, item) { var $result = $([]); if(this.editButton) { $result = $result.add(this._createEditButton(item)); } if(this.deleteButton) { $result = $result.add(this._createDeleteButton(item)); } return $result; }, filterTemplate: function() { var $result = this._createSearchButton(); return this.clearFilterButton ? $result.add(this._createClearFilterButton()) : $result; }, insertTemplate: function() { return this._createInsertButton(); }, editTemplate: function() { return this._createUpdateButton().add(this._createCancelEditButton()); }, _createFilterSwitchButton: function() { return this._createOnOffSwitchButton("filtering", this.searchModeButtonClass, true); }, _createInsertSwitchButton: function() { return this._createOnOffSwitchButton("inserting", this.insertModeButtonClass, false); }, _createOnOffSwitchButton: function(option, cssClass, isOnInitially) { var isOn = isOnInitially; var updateButtonState = $.proxy(function() { $button.toggleClass(this.modeOnButtonClass, isOn); }, this); var $button = this._createGridButton(this.modeButtonClass + " " + cssClass, "", function(grid) { isOn = !isOn; grid.option(option, isOn); updateButtonState(); }); updateButtonState(); return $button; }, _createModeSwitchButton: function() { var isInserting = false; var updateButtonState = $.proxy(function() { $button.attr("title", isInserting ? this.searchModeButtonTooltip : this.insertModeButtonTooltip) .toggleClass(this.insertModeButtonClass, !isInserting) .toggleClass(this.searchModeButtonClass, isInserting); }, this); var $button = this._createGridButton(this.modeButtonClass, "", function(grid) { isInserting = !isInserting; grid.option("inserting", isInserting); grid.option("filtering", !isInserting); updateButtonState(); }); updateButtonState(); return $button; }, _createEditButton: function(item) { return this._createGridButton(this.editButtonClass, this.editButtonTooltip, function(grid, e) { grid.editItem(item); e.stopPropagation(); }); }, _createDeleteButton: function(item) { return this._createGridButton(this.deleteButtonClass, this.deleteButtonTooltip, function(grid, e) { grid.deleteItem(item); e.stopPropagation(); }); }, _createSearchButton: function() { return this._createGridButton(this.searchButtonClass, this.searchButtonTooltip, function(grid) { grid.search(); }); }, _createClearFilterButton: function() { return this._createGridButton(this.clearFilterButtonClass, this.clearFilterButtonTooltip, function(grid) { grid.clearFilter(); }); }, _createInsertButton: function() { return this._createGridButton(this.insertButtonClass, this.insertButtonTooltip, function(grid) { grid.insertItem().done(function() { grid.clearInsert(); }); }); }, _createUpdateButton: function() { return this._createGridButton(this.updateButtonClass, this.updateButtonTooltip, function(grid, e) { grid.updateItem(); e.stopPropagation(); }); }, _createCancelEditButton: function() { return this._createGridButton(this.cancelEditButtonClass, this.cancelEditButtonTooltip, function(grid, e) { grid.cancelEdit(); e.stopPropagation(); }); }, _createGridButton: function(cls, tooltip, clickHandler) { var grid = this._grid; return $("<input>").addClass(this.buttonClass) .addClass(cls) .attr({ type: "button", title: tooltip }) .on("click", function(e) { clickHandler(grid, e); }); }, editValue: function() { return ""; } }); jsGrid.fields.control = jsGrid.ControlField = ControlField; }(jsGrid, jQuery)); <MSG> Merge branch 'master' of https://github.com/tabalinas/jsgrid <DFF> @@ -22,6 +22,8 @@ PAGE_INDEX_PLACEHOLDER = "{pageIndex}", PAGE_COUNT_PLACEHOLDER = "{pageCount}", ITEM_COUNT_PLACEHOLDER = "{itemCount}", + ITEM_INDEX_FROM_PLACEHOLDER = "{itemIndexFrom}", + ITEM_INDEX_TO_PLACEHOLDER = "{itemIndexTo}", EMPTY_HREF = "javascript:void(0);"; @@ -821,6 +823,8 @@ var pageIndex = this.pageIndex, pageCount = this._pagesCount(), itemCount = this._itemsCount(), + itemIndexFrom = ((this.pageIndex - 1) * this.pageSize + 1), + itemIndexTo = Math.min((this.pageIndex * this.pageSize), itemCount), pagerParts = this.pagerFormat.split(" "); return $.map(pagerParts, $.proxy(function(pagerPart) { @@ -842,6 +846,10 @@ result = pageCount; } else if(pagerPart === ITEM_COUNT_PLACEHOLDER) { result = itemCount; + } else if (pagerPart === ITEM_INDEX_FROM_PLACEHOLDER) { + result = itemIndexFrom; + } else if (pagerPart === ITEM_INDEX_TO_PLACEHOLDER) { + result = itemIndexTo; } return $.isArray(result) ? result.concat([" "]) : [result, " "];
8
Merge branch 'master' of https://github.com/tabalinas/jsgrid
0
.js
js
mit
tabalinas/jsgrid
10063546
<NME> FileReader.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.IO; using System.Text; namespace AvaloniaEdit.Utils { /// <summary> /// Class that can open text files with auto-detection of the encoding. /// </summary> internal static class FileReader { /// <summary> /// Gets if the given encoding is a Unicode encoding (UTF). /// </summary> /// <remarks> /// Returns true for UTF-7, UTF-8, UTF-16 LE, UTF-16 BE, UTF-32 LE and UTF-32 BE. /// Returns false for all other encodings. /// </remarks> public static bool IsUnicode(Encoding encoding) { if (encoding == null) throw new ArgumentNullException(nameof(encoding)); switch (encoding) { case UnicodeEncoding _: case UTF8Encoding _: return true; default: return false; } //switch (encoding) { // case 65000: // UTF-7 // case 65001: // UTF-8 // case 1200: // UTF-16 LE // case 1201: // UTF-16 BE // case 12000: // UTF-32 LE // case 12001: // UTF-32 BE // return true; // default: // return false; //} } private static bool IsAsciiCompatible(Encoding encoding) { var bytes = encoding.GetBytes("Az"); return bytes.Length == 2 && bytes[0] == 'A' && bytes[1] == 'z'; } private static Encoding RemoveBom(Encoding encoding) { if (encoding is UTF8Encoding) { return UTF8NoBOM; } return encoding; //switch (encoding.CodePage) { // case 65001: // UTF-8 // return UTF8NoBOM; // default: // return encoding; //} } /// <summary> /// Reads the content of the given stream. /// </summary> /// <param name="stream">The stream to read. /// The stream must support seeking and must be positioned at its beginning.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>The file content as string.</returns> public static string ReadFileContent(Stream stream, Encoding defaultEncoding) { using (var reader = OpenStream(stream, defaultEncoding)) { return reader.ReadToEnd(); } } /// <summary> /// Reads the content of the file. /// </summary> /// <param name="fileName">The file name.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>The file content as string.</returns> public static string ReadFileContent(string fileName, Encoding defaultEncoding) { throw new NotImplementedException(); //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { // return ReadFileContent(fs, defaultEncoding); //} } /// <summary> /// Opens the specified file for reading. /// </summary> /// <param name="fileName">The file to open.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>Returns a StreamReader that reads from the stream. Use /// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns> public static StreamReader OpenFile(string fileName, Encoding defaultEncoding) { throw new NotImplementedException(); //if (fileName == null) // throw new ArgumentNullException("fileName"); //FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); //try { // return OpenStream(fs, defaultEncoding); // // don't use finally: the stream must be kept open until the StreamReader closes it //} catch { // fs.Dispose(); // throw; //} } /// <summary> /// Opens the specified stream for reading. /// </summary> /// <param name="stream">The stream to open.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>Returns a StreamReader that reads from the stream. Use /// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns> public static StreamReader OpenStream(Stream stream, Encoding defaultEncoding) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (stream.Position != 0) throw new ArgumentException("stream is not positioned at beginning.", nameof(stream)); if (defaultEncoding == null) throw new ArgumentNullException(nameof(defaultEncoding)); if (stream.Length >= 2) { // the autodetection of StreamReader is not capable of detecting the difference // between ISO-8859-1 and UTF-8 without BOM. var firstByte = stream.ReadByte(); var secondByte = stream.ReadByte(); switch ((firstByte << 8) | secondByte) { case 0x0000: // either UTF-32 Big Endian or a binary file; use StreamReader case 0xfffe: // Unicode BOM (UTF-16 LE or UTF-32 LE) case 0xfeff: // UTF-16 BE BOM case 0xefbb: // start of UTF-8 BOM // StreamReader autodetection works stream.Position = 0; return new StreamReader(stream); default: return AutoDetect(stream, (byte) firstByte, (byte) secondByte, defaultEncoding); } } return new StreamReader(stream, defaultEncoding); } // ReSharper disable once InconsistentNaming private static readonly Encoding UTF8NoBOM = new UTF8Encoding(false); private static StreamReader AutoDetect(Stream fs, byte firstByte, byte secondByte, Encoding defaultEncoding) { var max = (int)Math.Min(fs.Length, 500000); // look at max. 500 KB // ReSharper disable InconsistentNaming const int ASCII = 0; const int Error = 1; const int UTF8 = 2; const int UTF8Sequence = 3; // ReSharper restore InconsistentNaming var state = ASCII; var sequenceLength = 0; for (var i = 0; i < max; i++) { byte b; if (i == 0) { b = firstByte; } else if (i == 1) { b = secondByte; } else { b = (byte)fs.ReadByte(); } if (b < 0x80) { // normal ASCII character if (state == UTF8Sequence) { state = Error; break; } } else if (b < 0xc0) { // 10xxxxxx : continues UTF8 byte sequence if (state == UTF8Sequence) { --sequenceLength; if (sequenceLength < 0) { state = Error; break; } else if (sequenceLength == 0) { state = UTF8; } } else { state = Error; break; } } else if (b >= 0xc2 && b < 0xf5) { // beginning of byte sequence if (state == UTF8 || state == ASCII) { state = UTF8Sequence; if (b < 0xe0) { sequenceLength = 1; // one more byte following } else if (b < 0xf0) { sequenceLength = 2; // two more bytes following } else { sequenceLength = 3; // three more bytes following } } else { state = Error; break; } } else { // 0xc0, 0xc1, 0xf5 to 0xff are invalid in UTF-8 (see RFC 3629) state = Error; break; } } fs.Position = 0; switch (state) { case ASCII: // TODO: Encoding.ASCII return new StreamReader(fs, IsAsciiCompatible(defaultEncoding) ? RemoveBom(defaultEncoding) : Encoding.UTF8); case Error: // When the file seems to be non-UTF8, // we read it using the user-specified encoding so it is saved again // using that encoding. if (IsUnicode(defaultEncoding)) { // the file is not Unicode, so don't read it using Unicode even if the // user has choosen Unicode as the default encoding. defaultEncoding = Encoding.UTF8; // use system encoding instead } return new StreamReader(fs, RemoveBom(defaultEncoding)); default: return new StreamReader(fs, UTF8NoBOM); } } } } <MSG> Merge pull request #202 from AlphaNecron/dev make FileReader public <DFF> @@ -25,7 +25,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Class that can open text files with auto-detection of the encoding. /// </summary> - internal static class FileReader + public static class FileReader { /// <summary> /// Gets if the given encoding is a Unicode encoding (UTF).
1
Merge pull request #202 from AlphaNecron/dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063547
<NME> FileReader.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.IO; using System.Text; namespace AvaloniaEdit.Utils { /// <summary> /// Class that can open text files with auto-detection of the encoding. /// </summary> internal static class FileReader { /// <summary> /// Gets if the given encoding is a Unicode encoding (UTF). /// </summary> /// <remarks> /// Returns true for UTF-7, UTF-8, UTF-16 LE, UTF-16 BE, UTF-32 LE and UTF-32 BE. /// Returns false for all other encodings. /// </remarks> public static bool IsUnicode(Encoding encoding) { if (encoding == null) throw new ArgumentNullException(nameof(encoding)); switch (encoding) { case UnicodeEncoding _: case UTF8Encoding _: return true; default: return false; } //switch (encoding) { // case 65000: // UTF-7 // case 65001: // UTF-8 // case 1200: // UTF-16 LE // case 1201: // UTF-16 BE // case 12000: // UTF-32 LE // case 12001: // UTF-32 BE // return true; // default: // return false; //} } private static bool IsAsciiCompatible(Encoding encoding) { var bytes = encoding.GetBytes("Az"); return bytes.Length == 2 && bytes[0] == 'A' && bytes[1] == 'z'; } private static Encoding RemoveBom(Encoding encoding) { if (encoding is UTF8Encoding) { return UTF8NoBOM; } return encoding; //switch (encoding.CodePage) { // case 65001: // UTF-8 // return UTF8NoBOM; // default: // return encoding; //} } /// <summary> /// Reads the content of the given stream. /// </summary> /// <param name="stream">The stream to read. /// The stream must support seeking and must be positioned at its beginning.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>The file content as string.</returns> public static string ReadFileContent(Stream stream, Encoding defaultEncoding) { using (var reader = OpenStream(stream, defaultEncoding)) { return reader.ReadToEnd(); } } /// <summary> /// Reads the content of the file. /// </summary> /// <param name="fileName">The file name.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>The file content as string.</returns> public static string ReadFileContent(string fileName, Encoding defaultEncoding) { throw new NotImplementedException(); //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { // return ReadFileContent(fs, defaultEncoding); //} } /// <summary> /// Opens the specified file for reading. /// </summary> /// <param name="fileName">The file to open.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>Returns a StreamReader that reads from the stream. Use /// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns> public static StreamReader OpenFile(string fileName, Encoding defaultEncoding) { throw new NotImplementedException(); //if (fileName == null) // throw new ArgumentNullException("fileName"); //FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); //try { // return OpenStream(fs, defaultEncoding); // // don't use finally: the stream must be kept open until the StreamReader closes it //} catch { // fs.Dispose(); // throw; //} } /// <summary> /// Opens the specified stream for reading. /// </summary> /// <param name="stream">The stream to open.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>Returns a StreamReader that reads from the stream. Use /// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns> public static StreamReader OpenStream(Stream stream, Encoding defaultEncoding) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (stream.Position != 0) throw new ArgumentException("stream is not positioned at beginning.", nameof(stream)); if (defaultEncoding == null) throw new ArgumentNullException(nameof(defaultEncoding)); if (stream.Length >= 2) { // the autodetection of StreamReader is not capable of detecting the difference // between ISO-8859-1 and UTF-8 without BOM. var firstByte = stream.ReadByte(); var secondByte = stream.ReadByte(); switch ((firstByte << 8) | secondByte) { case 0x0000: // either UTF-32 Big Endian or a binary file; use StreamReader case 0xfffe: // Unicode BOM (UTF-16 LE or UTF-32 LE) case 0xfeff: // UTF-16 BE BOM case 0xefbb: // start of UTF-8 BOM // StreamReader autodetection works stream.Position = 0; return new StreamReader(stream); default: return AutoDetect(stream, (byte) firstByte, (byte) secondByte, defaultEncoding); } } return new StreamReader(stream, defaultEncoding); } // ReSharper disable once InconsistentNaming private static readonly Encoding UTF8NoBOM = new UTF8Encoding(false); private static StreamReader AutoDetect(Stream fs, byte firstByte, byte secondByte, Encoding defaultEncoding) { var max = (int)Math.Min(fs.Length, 500000); // look at max. 500 KB // ReSharper disable InconsistentNaming const int ASCII = 0; const int Error = 1; const int UTF8 = 2; const int UTF8Sequence = 3; // ReSharper restore InconsistentNaming var state = ASCII; var sequenceLength = 0; for (var i = 0; i < max; i++) { byte b; if (i == 0) { b = firstByte; } else if (i == 1) { b = secondByte; } else { b = (byte)fs.ReadByte(); } if (b < 0x80) { // normal ASCII character if (state == UTF8Sequence) { state = Error; break; } } else if (b < 0xc0) { // 10xxxxxx : continues UTF8 byte sequence if (state == UTF8Sequence) { --sequenceLength; if (sequenceLength < 0) { state = Error; break; } else if (sequenceLength == 0) { state = UTF8; } } else { state = Error; break; } } else if (b >= 0xc2 && b < 0xf5) { // beginning of byte sequence if (state == UTF8 || state == ASCII) { state = UTF8Sequence; if (b < 0xe0) { sequenceLength = 1; // one more byte following } else if (b < 0xf0) { sequenceLength = 2; // two more bytes following } else { sequenceLength = 3; // three more bytes following } } else { state = Error; break; } } else { // 0xc0, 0xc1, 0xf5 to 0xff are invalid in UTF-8 (see RFC 3629) state = Error; break; } } fs.Position = 0; switch (state) { case ASCII: // TODO: Encoding.ASCII return new StreamReader(fs, IsAsciiCompatible(defaultEncoding) ? RemoveBom(defaultEncoding) : Encoding.UTF8); case Error: // When the file seems to be non-UTF8, // we read it using the user-specified encoding so it is saved again // using that encoding. if (IsUnicode(defaultEncoding)) { // the file is not Unicode, so don't read it using Unicode even if the // user has choosen Unicode as the default encoding. defaultEncoding = Encoding.UTF8; // use system encoding instead } return new StreamReader(fs, RemoveBom(defaultEncoding)); default: return new StreamReader(fs, UTF8NoBOM); } } } } <MSG> Merge pull request #202 from AlphaNecron/dev make FileReader public <DFF> @@ -25,7 +25,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Class that can open text files with auto-detection of the encoding. /// </summary> - internal static class FileReader + public static class FileReader { /// <summary> /// Gets if the given encoding is a Unicode encoding (UTF).
1
Merge pull request #202 from AlphaNecron/dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063548
<NME> FileReader.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.IO; using System.Text; namespace AvaloniaEdit.Utils { /// <summary> /// Class that can open text files with auto-detection of the encoding. /// </summary> internal static class FileReader { /// <summary> /// Gets if the given encoding is a Unicode encoding (UTF). /// </summary> /// <remarks> /// Returns true for UTF-7, UTF-8, UTF-16 LE, UTF-16 BE, UTF-32 LE and UTF-32 BE. /// Returns false for all other encodings. /// </remarks> public static bool IsUnicode(Encoding encoding) { if (encoding == null) throw new ArgumentNullException(nameof(encoding)); switch (encoding) { case UnicodeEncoding _: case UTF8Encoding _: return true; default: return false; } //switch (encoding) { // case 65000: // UTF-7 // case 65001: // UTF-8 // case 1200: // UTF-16 LE // case 1201: // UTF-16 BE // case 12000: // UTF-32 LE // case 12001: // UTF-32 BE // return true; // default: // return false; //} } private static bool IsAsciiCompatible(Encoding encoding) { var bytes = encoding.GetBytes("Az"); return bytes.Length == 2 && bytes[0] == 'A' && bytes[1] == 'z'; } private static Encoding RemoveBom(Encoding encoding) { if (encoding is UTF8Encoding) { return UTF8NoBOM; } return encoding; //switch (encoding.CodePage) { // case 65001: // UTF-8 // return UTF8NoBOM; // default: // return encoding; //} } /// <summary> /// Reads the content of the given stream. /// </summary> /// <param name="stream">The stream to read. /// The stream must support seeking and must be positioned at its beginning.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>The file content as string.</returns> public static string ReadFileContent(Stream stream, Encoding defaultEncoding) { using (var reader = OpenStream(stream, defaultEncoding)) { return reader.ReadToEnd(); } } /// <summary> /// Reads the content of the file. /// </summary> /// <param name="fileName">The file name.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>The file content as string.</returns> public static string ReadFileContent(string fileName, Encoding defaultEncoding) { throw new NotImplementedException(); //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { // return ReadFileContent(fs, defaultEncoding); //} } /// <summary> /// Opens the specified file for reading. /// </summary> /// <param name="fileName">The file to open.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>Returns a StreamReader that reads from the stream. Use /// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns> public static StreamReader OpenFile(string fileName, Encoding defaultEncoding) { throw new NotImplementedException(); //if (fileName == null) // throw new ArgumentNullException("fileName"); //FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); //try { // return OpenStream(fs, defaultEncoding); // // don't use finally: the stream must be kept open until the StreamReader closes it //} catch { // fs.Dispose(); // throw; //} } /// <summary> /// Opens the specified stream for reading. /// </summary> /// <param name="stream">The stream to open.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>Returns a StreamReader that reads from the stream. Use /// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns> public static StreamReader OpenStream(Stream stream, Encoding defaultEncoding) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (stream.Position != 0) throw new ArgumentException("stream is not positioned at beginning.", nameof(stream)); if (defaultEncoding == null) throw new ArgumentNullException(nameof(defaultEncoding)); if (stream.Length >= 2) { // the autodetection of StreamReader is not capable of detecting the difference // between ISO-8859-1 and UTF-8 without BOM. var firstByte = stream.ReadByte(); var secondByte = stream.ReadByte(); switch ((firstByte << 8) | secondByte) { case 0x0000: // either UTF-32 Big Endian or a binary file; use StreamReader case 0xfffe: // Unicode BOM (UTF-16 LE or UTF-32 LE) case 0xfeff: // UTF-16 BE BOM case 0xefbb: // start of UTF-8 BOM // StreamReader autodetection works stream.Position = 0; return new StreamReader(stream); default: return AutoDetect(stream, (byte) firstByte, (byte) secondByte, defaultEncoding); } } return new StreamReader(stream, defaultEncoding); } // ReSharper disable once InconsistentNaming private static readonly Encoding UTF8NoBOM = new UTF8Encoding(false); private static StreamReader AutoDetect(Stream fs, byte firstByte, byte secondByte, Encoding defaultEncoding) { var max = (int)Math.Min(fs.Length, 500000); // look at max. 500 KB // ReSharper disable InconsistentNaming const int ASCII = 0; const int Error = 1; const int UTF8 = 2; const int UTF8Sequence = 3; // ReSharper restore InconsistentNaming var state = ASCII; var sequenceLength = 0; for (var i = 0; i < max; i++) { byte b; if (i == 0) { b = firstByte; } else if (i == 1) { b = secondByte; } else { b = (byte)fs.ReadByte(); } if (b < 0x80) { // normal ASCII character if (state == UTF8Sequence) { state = Error; break; } } else if (b < 0xc0) { // 10xxxxxx : continues UTF8 byte sequence if (state == UTF8Sequence) { --sequenceLength; if (sequenceLength < 0) { state = Error; break; } else if (sequenceLength == 0) { state = UTF8; } } else { state = Error; break; } } else if (b >= 0xc2 && b < 0xf5) { // beginning of byte sequence if (state == UTF8 || state == ASCII) { state = UTF8Sequence; if (b < 0xe0) { sequenceLength = 1; // one more byte following } else if (b < 0xf0) { sequenceLength = 2; // two more bytes following } else { sequenceLength = 3; // three more bytes following } } else { state = Error; break; } } else { // 0xc0, 0xc1, 0xf5 to 0xff are invalid in UTF-8 (see RFC 3629) state = Error; break; } } fs.Position = 0; switch (state) { case ASCII: // TODO: Encoding.ASCII return new StreamReader(fs, IsAsciiCompatible(defaultEncoding) ? RemoveBom(defaultEncoding) : Encoding.UTF8); case Error: // When the file seems to be non-UTF8, // we read it using the user-specified encoding so it is saved again // using that encoding. if (IsUnicode(defaultEncoding)) { // the file is not Unicode, so don't read it using Unicode even if the // user has choosen Unicode as the default encoding. defaultEncoding = Encoding.UTF8; // use system encoding instead } return new StreamReader(fs, RemoveBom(defaultEncoding)); default: return new StreamReader(fs, UTF8NoBOM); } } } } <MSG> Merge pull request #202 from AlphaNecron/dev make FileReader public <DFF> @@ -25,7 +25,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Class that can open text files with auto-detection of the encoding. /// </summary> - internal static class FileReader + public static class FileReader { /// <summary> /// Gets if the given encoding is a Unicode encoding (UTF).
1
Merge pull request #202 from AlphaNecron/dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063549
<NME> FileReader.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.IO; using System.Text; namespace AvaloniaEdit.Utils { /// <summary> /// Class that can open text files with auto-detection of the encoding. /// </summary> internal static class FileReader { /// <summary> /// Gets if the given encoding is a Unicode encoding (UTF). /// </summary> /// <remarks> /// Returns true for UTF-7, UTF-8, UTF-16 LE, UTF-16 BE, UTF-32 LE and UTF-32 BE. /// Returns false for all other encodings. /// </remarks> public static bool IsUnicode(Encoding encoding) { if (encoding == null) throw new ArgumentNullException(nameof(encoding)); switch (encoding) { case UnicodeEncoding _: case UTF8Encoding _: return true; default: return false; } //switch (encoding) { // case 65000: // UTF-7 // case 65001: // UTF-8 // case 1200: // UTF-16 LE // case 1201: // UTF-16 BE // case 12000: // UTF-32 LE // case 12001: // UTF-32 BE // return true; // default: // return false; //} } private static bool IsAsciiCompatible(Encoding encoding) { var bytes = encoding.GetBytes("Az"); return bytes.Length == 2 && bytes[0] == 'A' && bytes[1] == 'z'; } private static Encoding RemoveBom(Encoding encoding) { if (encoding is UTF8Encoding) { return UTF8NoBOM; } return encoding; //switch (encoding.CodePage) { // case 65001: // UTF-8 // return UTF8NoBOM; // default: // return encoding; //} } /// <summary> /// Reads the content of the given stream. /// </summary> /// <param name="stream">The stream to read. /// The stream must support seeking and must be positioned at its beginning.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>The file content as string.</returns> public static string ReadFileContent(Stream stream, Encoding defaultEncoding) { using (var reader = OpenStream(stream, defaultEncoding)) { return reader.ReadToEnd(); } } /// <summary> /// Reads the content of the file. /// </summary> /// <param name="fileName">The file name.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>The file content as string.</returns> public static string ReadFileContent(string fileName, Encoding defaultEncoding) { throw new NotImplementedException(); //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { // return ReadFileContent(fs, defaultEncoding); //} } /// <summary> /// Opens the specified file for reading. /// </summary> /// <param name="fileName">The file to open.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>Returns a StreamReader that reads from the stream. Use /// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns> public static StreamReader OpenFile(string fileName, Encoding defaultEncoding) { throw new NotImplementedException(); //if (fileName == null) // throw new ArgumentNullException("fileName"); //FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); //try { // return OpenStream(fs, defaultEncoding); // // don't use finally: the stream must be kept open until the StreamReader closes it //} catch { // fs.Dispose(); // throw; //} } /// <summary> /// Opens the specified stream for reading. /// </summary> /// <param name="stream">The stream to open.</param> /// <param name="defaultEncoding">The encoding to use if the encoding cannot be auto-detected.</param> /// <returns>Returns a StreamReader that reads from the stream. Use /// <see cref="StreamReader.CurrentEncoding"/> to get the encoding that was used.</returns> public static StreamReader OpenStream(Stream stream, Encoding defaultEncoding) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (stream.Position != 0) throw new ArgumentException("stream is not positioned at beginning.", nameof(stream)); if (defaultEncoding == null) throw new ArgumentNullException(nameof(defaultEncoding)); if (stream.Length >= 2) { // the autodetection of StreamReader is not capable of detecting the difference // between ISO-8859-1 and UTF-8 without BOM. var firstByte = stream.ReadByte(); var secondByte = stream.ReadByte(); switch ((firstByte << 8) | secondByte) { case 0x0000: // either UTF-32 Big Endian or a binary file; use StreamReader case 0xfffe: // Unicode BOM (UTF-16 LE or UTF-32 LE) case 0xfeff: // UTF-16 BE BOM case 0xefbb: // start of UTF-8 BOM // StreamReader autodetection works stream.Position = 0; return new StreamReader(stream); default: return AutoDetect(stream, (byte) firstByte, (byte) secondByte, defaultEncoding); } } return new StreamReader(stream, defaultEncoding); } // ReSharper disable once InconsistentNaming private static readonly Encoding UTF8NoBOM = new UTF8Encoding(false); private static StreamReader AutoDetect(Stream fs, byte firstByte, byte secondByte, Encoding defaultEncoding) { var max = (int)Math.Min(fs.Length, 500000); // look at max. 500 KB // ReSharper disable InconsistentNaming const int ASCII = 0; const int Error = 1; const int UTF8 = 2; const int UTF8Sequence = 3; // ReSharper restore InconsistentNaming var state = ASCII; var sequenceLength = 0; for (var i = 0; i < max; i++) { byte b; if (i == 0) { b = firstByte; } else if (i == 1) { b = secondByte; } else { b = (byte)fs.ReadByte(); } if (b < 0x80) { // normal ASCII character if (state == UTF8Sequence) { state = Error; break; } } else if (b < 0xc0) { // 10xxxxxx : continues UTF8 byte sequence if (state == UTF8Sequence) { --sequenceLength; if (sequenceLength < 0) { state = Error; break; } else if (sequenceLength == 0) { state = UTF8; } } else { state = Error; break; } } else if (b >= 0xc2 && b < 0xf5) { // beginning of byte sequence if (state == UTF8 || state == ASCII) { state = UTF8Sequence; if (b < 0xe0) { sequenceLength = 1; // one more byte following } else if (b < 0xf0) { sequenceLength = 2; // two more bytes following } else { sequenceLength = 3; // three more bytes following } } else { state = Error; break; } } else { // 0xc0, 0xc1, 0xf5 to 0xff are invalid in UTF-8 (see RFC 3629) state = Error; break; } } fs.Position = 0; switch (state) { case ASCII: // TODO: Encoding.ASCII return new StreamReader(fs, IsAsciiCompatible(defaultEncoding) ? RemoveBom(defaultEncoding) : Encoding.UTF8); case Error: // When the file seems to be non-UTF8, // we read it using the user-specified encoding so it is saved again // using that encoding. if (IsUnicode(defaultEncoding)) { // the file is not Unicode, so don't read it using Unicode even if the // user has choosen Unicode as the default encoding. defaultEncoding = Encoding.UTF8; // use system encoding instead } return new StreamReader(fs, RemoveBom(defaultEncoding)); default: return new StreamReader(fs, UTF8NoBOM); } } } } <MSG> Merge pull request #202 from AlphaNecron/dev make FileReader public <DFF> @@ -25,7 +25,7 @@ namespace AvaloniaEdit.Utils /// <summary> /// Class that can open text files with auto-detection of the encoding. /// </summary> - internal static class FileReader + public static class FileReader { /// <summary> /// Gets if the given encoding is a Unicode encoding (UTF).
1
Merge pull request #202 from AlphaNecron/dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit