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
10063150
<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 TextDocument _document; private TextView _textView; private volatile int _firstVisibleLine = -1; private volatile int _lastVisibleLine = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; 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 (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { if (_textView != null) _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) _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 map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _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; if (_model.IsStopped) return; int firstChangedLine = int.MaxValue; int lastChangedLine = -1; foreach (var range in e.ranges) { firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); } bool areChangedLinesVisible = firstChangedLine >= _firstVisibleLine || lastChangedLine >= _firstVisibleLine || firstChangedLine <= _lastVisibleLine || lastChangedLine <= _lastVisibleLine; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); int totalLines = _document.Lines.Count - 1; iniIndex = Clamp(iniIndex, 0, totalLines); endIndexLine = Clamp(endIndexLine, 0, totalLines); DocumentLine iniLine = _document.Lines[iniIndex]; DocumentLine lastLine = _document.Lines[endIndexLine]; _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); }, DispatcherPriority.Render - 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> Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes) <DFF> @@ -24,8 +24,8 @@ namespace AvaloniaEdit.TextMate private TextDocument _document; private TextView _textView; - private volatile int _firstVisibleLine = -1; - private volatile int _lastVisibleLine = -1; + private volatile int _firstVisibleLineIndex = -1; + private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; @@ -54,14 +54,13 @@ namespace AvaloniaEdit.TextMate if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; - _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; - _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; + _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; + _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { - if (_textView != null) - _textView.VisualLinesChanged -= TextView_VisualLinesChanged; + _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) @@ -175,38 +174,40 @@ namespace AvaloniaEdit.TextMate if (_model.IsStopped) return; - int firstChangedLine = int.MaxValue; - int lastChangedLine = -1; + int firstChangedLineIndex = int.MaxValue; + int lastChangedLineIndex = -1; foreach (var range in e.ranges) { - firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); - lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); + firstChangedLineIndex = Math.Min(range.fromLineNumber - 1, firstChangedLineIndex); + lastChangedLineIndex = Math.Max(range.toLineNumber - 1, lastChangedLineIndex); } bool areChangedLinesVisible = - firstChangedLine >= _firstVisibleLine || - lastChangedLine >= _firstVisibleLine || - firstChangedLine <= _lastVisibleLine || - lastChangedLine <= _lastVisibleLine; + firstChangedLineIndex >= _firstVisibleLineIndex || + lastChangedLineIndex >= _firstVisibleLineIndex || + firstChangedLineIndex <= _lastVisibleLineIndex || + lastChangedLineIndex <= _lastVisibleLineIndex; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { - int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); - int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); + int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); + int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; - iniIndex = Clamp(iniIndex, 0, totalLines); - endIndexLine = Clamp(endIndexLine, 0, totalLines); + firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); + lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); - DocumentLine iniLine = _document.Lines[iniIndex]; - DocumentLine lastLine = _document.Lines[endIndexLine]; + DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; + DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; - _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); + _textView.Redraw( + firstLineToRedraw.Offset, + (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }, DispatcherPriority.Render - 1); }
22
Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes)
21
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063151
<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 TextDocument _document; private TextView _textView; private volatile int _firstVisibleLine = -1; private volatile int _lastVisibleLine = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; 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 (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { if (_textView != null) _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) _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 map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _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; if (_model.IsStopped) return; int firstChangedLine = int.MaxValue; int lastChangedLine = -1; foreach (var range in e.ranges) { firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); } bool areChangedLinesVisible = firstChangedLine >= _firstVisibleLine || lastChangedLine >= _firstVisibleLine || firstChangedLine <= _lastVisibleLine || lastChangedLine <= _lastVisibleLine; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); int totalLines = _document.Lines.Count - 1; iniIndex = Clamp(iniIndex, 0, totalLines); endIndexLine = Clamp(endIndexLine, 0, totalLines); DocumentLine iniLine = _document.Lines[iniIndex]; DocumentLine lastLine = _document.Lines[endIndexLine]; _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); }, DispatcherPriority.Render - 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> Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes) <DFF> @@ -24,8 +24,8 @@ namespace AvaloniaEdit.TextMate private TextDocument _document; private TextView _textView; - private volatile int _firstVisibleLine = -1; - private volatile int _lastVisibleLine = -1; + private volatile int _firstVisibleLineIndex = -1; + private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; @@ -54,14 +54,13 @@ namespace AvaloniaEdit.TextMate if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; - _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; - _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; + _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; + _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { - if (_textView != null) - _textView.VisualLinesChanged -= TextView_VisualLinesChanged; + _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) @@ -175,38 +174,40 @@ namespace AvaloniaEdit.TextMate if (_model.IsStopped) return; - int firstChangedLine = int.MaxValue; - int lastChangedLine = -1; + int firstChangedLineIndex = int.MaxValue; + int lastChangedLineIndex = -1; foreach (var range in e.ranges) { - firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); - lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); + firstChangedLineIndex = Math.Min(range.fromLineNumber - 1, firstChangedLineIndex); + lastChangedLineIndex = Math.Max(range.toLineNumber - 1, lastChangedLineIndex); } bool areChangedLinesVisible = - firstChangedLine >= _firstVisibleLine || - lastChangedLine >= _firstVisibleLine || - firstChangedLine <= _lastVisibleLine || - lastChangedLine <= _lastVisibleLine; + firstChangedLineIndex >= _firstVisibleLineIndex || + lastChangedLineIndex >= _firstVisibleLineIndex || + firstChangedLineIndex <= _lastVisibleLineIndex || + lastChangedLineIndex <= _lastVisibleLineIndex; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { - int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); - int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); + int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); + int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; - iniIndex = Clamp(iniIndex, 0, totalLines); - endIndexLine = Clamp(endIndexLine, 0, totalLines); + firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); + lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); - DocumentLine iniLine = _document.Lines[iniIndex]; - DocumentLine lastLine = _document.Lines[endIndexLine]; + DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; + DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; - _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); + _textView.Redraw( + firstLineToRedraw.Offset, + (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }, DispatcherPriority.Render - 1); }
22
Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes)
21
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063152
<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 TextDocument _document; private TextView _textView; private volatile int _firstVisibleLine = -1; private volatile int _lastVisibleLine = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; 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 (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { if (_textView != null) _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) _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 map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _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; if (_model.IsStopped) return; int firstChangedLine = int.MaxValue; int lastChangedLine = -1; foreach (var range in e.ranges) { firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); } bool areChangedLinesVisible = firstChangedLine >= _firstVisibleLine || lastChangedLine >= _firstVisibleLine || firstChangedLine <= _lastVisibleLine || lastChangedLine <= _lastVisibleLine; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); int totalLines = _document.Lines.Count - 1; iniIndex = Clamp(iniIndex, 0, totalLines); endIndexLine = Clamp(endIndexLine, 0, totalLines); DocumentLine iniLine = _document.Lines[iniIndex]; DocumentLine lastLine = _document.Lines[endIndexLine]; _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); }, DispatcherPriority.Render - 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> Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes) <DFF> @@ -24,8 +24,8 @@ namespace AvaloniaEdit.TextMate private TextDocument _document; private TextView _textView; - private volatile int _firstVisibleLine = -1; - private volatile int _lastVisibleLine = -1; + private volatile int _firstVisibleLineIndex = -1; + private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; @@ -54,14 +54,13 @@ namespace AvaloniaEdit.TextMate if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; - _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; - _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; + _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; + _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { - if (_textView != null) - _textView.VisualLinesChanged -= TextView_VisualLinesChanged; + _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) @@ -175,38 +174,40 @@ namespace AvaloniaEdit.TextMate if (_model.IsStopped) return; - int firstChangedLine = int.MaxValue; - int lastChangedLine = -1; + int firstChangedLineIndex = int.MaxValue; + int lastChangedLineIndex = -1; foreach (var range in e.ranges) { - firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); - lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); + firstChangedLineIndex = Math.Min(range.fromLineNumber - 1, firstChangedLineIndex); + lastChangedLineIndex = Math.Max(range.toLineNumber - 1, lastChangedLineIndex); } bool areChangedLinesVisible = - firstChangedLine >= _firstVisibleLine || - lastChangedLine >= _firstVisibleLine || - firstChangedLine <= _lastVisibleLine || - lastChangedLine <= _lastVisibleLine; + firstChangedLineIndex >= _firstVisibleLineIndex || + lastChangedLineIndex >= _firstVisibleLineIndex || + firstChangedLineIndex <= _lastVisibleLineIndex || + lastChangedLineIndex <= _lastVisibleLineIndex; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { - int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); - int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); + int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); + int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; - iniIndex = Clamp(iniIndex, 0, totalLines); - endIndexLine = Clamp(endIndexLine, 0, totalLines); + firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); + lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); - DocumentLine iniLine = _document.Lines[iniIndex]; - DocumentLine lastLine = _document.Lines[endIndexLine]; + DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; + DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; - _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); + _textView.Redraw( + firstLineToRedraw.Offset, + (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }, DispatcherPriority.Render - 1); }
22
Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes)
21
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063153
<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 TextDocument _document; private TextView _textView; private volatile int _firstVisibleLine = -1; private volatile int _lastVisibleLine = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; 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 (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { if (_textView != null) _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) _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 map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _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; if (_model.IsStopped) return; int firstChangedLine = int.MaxValue; int lastChangedLine = -1; foreach (var range in e.ranges) { firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); } bool areChangedLinesVisible = firstChangedLine >= _firstVisibleLine || lastChangedLine >= _firstVisibleLine || firstChangedLine <= _lastVisibleLine || lastChangedLine <= _lastVisibleLine; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); int totalLines = _document.Lines.Count - 1; iniIndex = Clamp(iniIndex, 0, totalLines); endIndexLine = Clamp(endIndexLine, 0, totalLines); DocumentLine iniLine = _document.Lines[iniIndex]; DocumentLine lastLine = _document.Lines[endIndexLine]; _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); }, DispatcherPriority.Render - 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> Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes) <DFF> @@ -24,8 +24,8 @@ namespace AvaloniaEdit.TextMate private TextDocument _document; private TextView _textView; - private volatile int _firstVisibleLine = -1; - private volatile int _lastVisibleLine = -1; + private volatile int _firstVisibleLineIndex = -1; + private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; @@ -54,14 +54,13 @@ namespace AvaloniaEdit.TextMate if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; - _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; - _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; + _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; + _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { - if (_textView != null) - _textView.VisualLinesChanged -= TextView_VisualLinesChanged; + _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) @@ -175,38 +174,40 @@ namespace AvaloniaEdit.TextMate if (_model.IsStopped) return; - int firstChangedLine = int.MaxValue; - int lastChangedLine = -1; + int firstChangedLineIndex = int.MaxValue; + int lastChangedLineIndex = -1; foreach (var range in e.ranges) { - firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); - lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); + firstChangedLineIndex = Math.Min(range.fromLineNumber - 1, firstChangedLineIndex); + lastChangedLineIndex = Math.Max(range.toLineNumber - 1, lastChangedLineIndex); } bool areChangedLinesVisible = - firstChangedLine >= _firstVisibleLine || - lastChangedLine >= _firstVisibleLine || - firstChangedLine <= _lastVisibleLine || - lastChangedLine <= _lastVisibleLine; + firstChangedLineIndex >= _firstVisibleLineIndex || + lastChangedLineIndex >= _firstVisibleLineIndex || + firstChangedLineIndex <= _lastVisibleLineIndex || + lastChangedLineIndex <= _lastVisibleLineIndex; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { - int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); - int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); + int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); + int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; - iniIndex = Clamp(iniIndex, 0, totalLines); - endIndexLine = Clamp(endIndexLine, 0, totalLines); + firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); + lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); - DocumentLine iniLine = _document.Lines[iniIndex]; - DocumentLine lastLine = _document.Lines[endIndexLine]; + DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; + DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; - _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); + _textView.Redraw( + firstLineToRedraw.Offset, + (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }, DispatcherPriority.Render - 1); }
22
Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes)
21
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063154
<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 TextDocument _document; private TextView _textView; private volatile int _firstVisibleLine = -1; private volatile int _lastVisibleLine = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; 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 (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { if (_textView != null) _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) _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 map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _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; if (_model.IsStopped) return; int firstChangedLine = int.MaxValue; int lastChangedLine = -1; foreach (var range in e.ranges) { firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); } bool areChangedLinesVisible = firstChangedLine >= _firstVisibleLine || lastChangedLine >= _firstVisibleLine || firstChangedLine <= _lastVisibleLine || lastChangedLine <= _lastVisibleLine; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); int totalLines = _document.Lines.Count - 1; iniIndex = Clamp(iniIndex, 0, totalLines); endIndexLine = Clamp(endIndexLine, 0, totalLines); DocumentLine iniLine = _document.Lines[iniIndex]; DocumentLine lastLine = _document.Lines[endIndexLine]; _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); }, DispatcherPriority.Render - 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> Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes) <DFF> @@ -24,8 +24,8 @@ namespace AvaloniaEdit.TextMate private TextDocument _document; private TextView _textView; - private volatile int _firstVisibleLine = -1; - private volatile int _lastVisibleLine = -1; + private volatile int _firstVisibleLineIndex = -1; + private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; @@ -54,14 +54,13 @@ namespace AvaloniaEdit.TextMate if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; - _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; - _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; + _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; + _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { - if (_textView != null) - _textView.VisualLinesChanged -= TextView_VisualLinesChanged; + _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) @@ -175,38 +174,40 @@ namespace AvaloniaEdit.TextMate if (_model.IsStopped) return; - int firstChangedLine = int.MaxValue; - int lastChangedLine = -1; + int firstChangedLineIndex = int.MaxValue; + int lastChangedLineIndex = -1; foreach (var range in e.ranges) { - firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); - lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); + firstChangedLineIndex = Math.Min(range.fromLineNumber - 1, firstChangedLineIndex); + lastChangedLineIndex = Math.Max(range.toLineNumber - 1, lastChangedLineIndex); } bool areChangedLinesVisible = - firstChangedLine >= _firstVisibleLine || - lastChangedLine >= _firstVisibleLine || - firstChangedLine <= _lastVisibleLine || - lastChangedLine <= _lastVisibleLine; + firstChangedLineIndex >= _firstVisibleLineIndex || + lastChangedLineIndex >= _firstVisibleLineIndex || + firstChangedLineIndex <= _lastVisibleLineIndex || + lastChangedLineIndex <= _lastVisibleLineIndex; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { - int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); - int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); + int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); + int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; - iniIndex = Clamp(iniIndex, 0, totalLines); - endIndexLine = Clamp(endIndexLine, 0, totalLines); + firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); + lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); - DocumentLine iniLine = _document.Lines[iniIndex]; - DocumentLine lastLine = _document.Lines[endIndexLine]; + DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; + DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; - _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); + _textView.Redraw( + firstLineToRedraw.Offset, + (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }, DispatcherPriority.Render - 1); }
22
Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes)
21
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063155
<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 TextDocument _document; private TextView _textView; private volatile int _firstVisibleLine = -1; private volatile int _lastVisibleLine = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; 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 (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { if (_textView != null) _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) _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 map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _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; if (_model.IsStopped) return; int firstChangedLine = int.MaxValue; int lastChangedLine = -1; foreach (var range in e.ranges) { firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); } bool areChangedLinesVisible = firstChangedLine >= _firstVisibleLine || lastChangedLine >= _firstVisibleLine || firstChangedLine <= _lastVisibleLine || lastChangedLine <= _lastVisibleLine; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); int totalLines = _document.Lines.Count - 1; iniIndex = Clamp(iniIndex, 0, totalLines); endIndexLine = Clamp(endIndexLine, 0, totalLines); DocumentLine iniLine = _document.Lines[iniIndex]; DocumentLine lastLine = _document.Lines[endIndexLine]; _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); }, DispatcherPriority.Render - 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> Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes) <DFF> @@ -24,8 +24,8 @@ namespace AvaloniaEdit.TextMate private TextDocument _document; private TextView _textView; - private volatile int _firstVisibleLine = -1; - private volatile int _lastVisibleLine = -1; + private volatile int _firstVisibleLineIndex = -1; + private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; @@ -54,14 +54,13 @@ namespace AvaloniaEdit.TextMate if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; - _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; - _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; + _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; + _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { - if (_textView != null) - _textView.VisualLinesChanged -= TextView_VisualLinesChanged; + _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) @@ -175,38 +174,40 @@ namespace AvaloniaEdit.TextMate if (_model.IsStopped) return; - int firstChangedLine = int.MaxValue; - int lastChangedLine = -1; + int firstChangedLineIndex = int.MaxValue; + int lastChangedLineIndex = -1; foreach (var range in e.ranges) { - firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); - lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); + firstChangedLineIndex = Math.Min(range.fromLineNumber - 1, firstChangedLineIndex); + lastChangedLineIndex = Math.Max(range.toLineNumber - 1, lastChangedLineIndex); } bool areChangedLinesVisible = - firstChangedLine >= _firstVisibleLine || - lastChangedLine >= _firstVisibleLine || - firstChangedLine <= _lastVisibleLine || - lastChangedLine <= _lastVisibleLine; + firstChangedLineIndex >= _firstVisibleLineIndex || + lastChangedLineIndex >= _firstVisibleLineIndex || + firstChangedLineIndex <= _lastVisibleLineIndex || + lastChangedLineIndex <= _lastVisibleLineIndex; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { - int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); - int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); + int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); + int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; - iniIndex = Clamp(iniIndex, 0, totalLines); - endIndexLine = Clamp(endIndexLine, 0, totalLines); + firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); + lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); - DocumentLine iniLine = _document.Lines[iniIndex]; - DocumentLine lastLine = _document.Lines[endIndexLine]; + DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; + DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; - _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); + _textView.Redraw( + firstLineToRedraw.Offset, + (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }, DispatcherPriority.Render - 1); }
22
Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes)
21
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063156
<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 TextDocument _document; private TextView _textView; private volatile int _firstVisibleLine = -1; private volatile int _lastVisibleLine = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; 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 (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { if (_textView != null) _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) _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 map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { _grammar = grammar; if (_model != null) { _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; if (_model.IsStopped) return; int firstChangedLine = int.MaxValue; int lastChangedLine = -1; foreach (var range in e.ranges) { firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); } bool areChangedLinesVisible = firstChangedLine >= _firstVisibleLine || lastChangedLine >= _firstVisibleLine || firstChangedLine <= _lastVisibleLine || lastChangedLine <= _lastVisibleLine; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); int totalLines = _document.Lines.Count - 1; iniIndex = Clamp(iniIndex, 0, totalLines); endIndexLine = Clamp(endIndexLine, 0, totalLines); DocumentLine iniLine = _document.Lines[iniIndex]; DocumentLine lastLine = _document.Lines[endIndexLine]; _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); }, DispatcherPriority.Render - 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> Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes) <DFF> @@ -24,8 +24,8 @@ namespace AvaloniaEdit.TextMate private TextDocument _document; private TextView _textView; - private volatile int _firstVisibleLine = -1; - private volatile int _lastVisibleLine = -1; + private volatile int _firstVisibleLineIndex = -1; + private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; private TextSegmentCollection<TextTransformation> _transformations; @@ -54,14 +54,13 @@ namespace AvaloniaEdit.TextMate if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; - _firstVisibleLine = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; - _lastVisibleLine = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; + _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; + _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } public void Dispose() { - if (_textView != null) - _textView.VisualLinesChanged -= TextView_VisualLinesChanged; + _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) @@ -175,38 +174,40 @@ namespace AvaloniaEdit.TextMate if (_model.IsStopped) return; - int firstChangedLine = int.MaxValue; - int lastChangedLine = -1; + int firstChangedLineIndex = int.MaxValue; + int lastChangedLineIndex = -1; foreach (var range in e.ranges) { - firstChangedLine = Math.Min(range.fromLineNumber - 1, firstChangedLine); - lastChangedLine = Math.Max(range.toLineNumber - 1, lastChangedLine); + firstChangedLineIndex = Math.Min(range.fromLineNumber - 1, firstChangedLineIndex); + lastChangedLineIndex = Math.Max(range.toLineNumber - 1, lastChangedLineIndex); } bool areChangedLinesVisible = - firstChangedLine >= _firstVisibleLine || - lastChangedLine >= _firstVisibleLine || - firstChangedLine <= _lastVisibleLine || - lastChangedLine <= _lastVisibleLine; + firstChangedLineIndex >= _firstVisibleLineIndex || + lastChangedLineIndex >= _firstVisibleLineIndex || + firstChangedLineIndex <= _lastVisibleLineIndex || + lastChangedLineIndex <= _lastVisibleLineIndex; if (!areChangedLinesVisible) return; Dispatcher.UIThread.Post(() => { - int iniIndex = Math.Max(firstChangedLine, _firstVisibleLine); - int endIndexLine = Math.Min(lastChangedLine, _lastVisibleLine); + int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); + int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; - iniIndex = Clamp(iniIndex, 0, totalLines); - endIndexLine = Clamp(endIndexLine, 0, totalLines); + firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); + lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); - DocumentLine iniLine = _document.Lines[iniIndex]; - DocumentLine lastLine = _document.Lines[endIndexLine]; + DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; + DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; - _textView.Redraw(iniLine.Offset, (lastLine.Offset + lastLine.TotalLength) - iniLine.Offset); + _textView.Redraw( + firstLineToRedraw.Offset, + (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }, DispatcherPriority.Render - 1); }
22
Rename variables in TextMateColoringTransformer (make clear we're managing 0-based line indexes)
21
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10063157
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063158
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063159
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063160
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063161
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063162
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063163
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063164
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063165
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063166
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063167
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063168
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063169
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063170
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063171
<NME> BackgroundGeometryBuilder.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Avalonia; using Avalonia.Controls.Primitives; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Rendering { /// <summary> /// Helper for creating a PathGeometry. /// </summary> public sealed class BackgroundGeometryBuilder { private double _cornerRadius; /// <summary> /// Gets/sets the radius of the rounded corners. /// </summary> public double CornerRadius { get { return _cornerRadius; } set { _cornerRadius = value; } } /// <summary> /// Gets/Sets whether to align to whole pixels. /// /// If BorderThickness is set to 0, the geometry is aligned to whole pixels. /// If BorderThickness is set to a non-zero value, the outer edge of the border is aligned /// to whole pixels. /// /// The default value is <c>false</c>. /// </summary> public bool AlignToWholePixels { get; set; } /// <summary> /// Gets/sets the border thickness. /// /// This property only has an effect if <c>AlignToWholePixels</c> is enabled. /// When using the resulting geometry to paint a border, set this property to the border thickness. /// Otherwise, leave the property set to the default value <c>0</c>. /// </summary> public double BorderThickness { get; set; } /// <summary> /// Gets/Sets whether to extend the rectangles to full width at line end. /// </summary> public bool ExtendToFullWidthAtLineEnd { get; set; } /// <summary> /// Creates a new BackgroundGeometryBuilder instance. /// </summary> public BackgroundGeometryBuilder() { } /// <summary> /// Adds the specified segment to the geometry. /// </summary> public void AddSegment(TextView textView, ISegment segment) { if (textView == null) throw new ArgumentNullException("textView"); Size pixelSize = PixelSnapHelpers.GetPixelSize(textView); foreach (Rect r in GetRectsForSegment(textView, segment, ExtendToFullWidthAtLineEnd)) { AddRectangle(pixelSize, r); } } /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload will align the coordinates according to /// <see cref="AlignToWholePixels"/>. /// Use the <see cref="AddRectangle(double,double,double,double)"/>-overload instead if the coordinates should not be aligned. /// </remarks> public void AddRectangle(TextView textView, Rect rectangle) { AddRectangle(PixelSnapHelpers.GetPixelSize(textView), rectangle); } private void AddRectangle(Size pixelSize, Rect r) { if (AlignToWholePixels) { double halfBorder = 0.5 * BorderThickness; AddRectangle(PixelSnapHelpers.Round(r.Left - halfBorder, pixelSize.Width) + halfBorder, PixelSnapHelpers.Round(r.Top - halfBorder, pixelSize.Height) + halfBorder, PixelSnapHelpers.Round(r.Right + halfBorder, pixelSize.Width) - halfBorder, PixelSnapHelpers.Round(r.Bottom + halfBorder, pixelSize.Height) - halfBorder); //Debug.WriteLine(r.ToString() + " -> " + new Rect(lastLeft, lastTop, lastRight-lastLeft, lastBottom-lastTop).ToString()); } else { AddRectangle(r.Left, r.Top, r.Right, r.Bottom); } } /// <summary> /// Calculates the list of rectangle where the segment in shown. /// This method usually returns one rectangle for each line inside the segment /// (but potentially more, e.g. when bidirectional text is involved). /// </summary> public static IEnumerable<Rect> GetRectsForSegment(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd = false) { if (textView == null) throw new ArgumentNullException("textView"); if (segment == null) throw new ArgumentNullException("segment"); return GetRectsForSegmentImpl(textView, segment, extendToFullWidthAtLineEnd); } private static IEnumerable<Rect> GetRectsForSegmentImpl(TextView textView, ISegment segment, bool extendToFullWidthAtLineEnd) { int segmentStart = segment.Offset; int segmentEnd = segment.Offset + segment.Length; segmentStart = segmentStart.CoerceValue(0, textView.Document.TextLength); segmentEnd = segmentEnd.CoerceValue(0, textView.Document.TextLength); TextViewPosition start; TextViewPosition end; if (segment is SelectionSegment) { SelectionSegment sel = (SelectionSegment)segment; start = new TextViewPosition(textView.Document.GetLocation(sel.StartOffset), sel.StartVisualColumn); end = new TextViewPosition(textView.Document.GetLocation(sel.EndOffset), sel.EndVisualColumn); } else { start = new TextViewPosition(textView.Document.GetLocation(segmentStart)); end = new TextViewPosition(textView.Document.GetLocation(segmentEnd)); } foreach (VisualLine vl in textView.VisualLines) { int vlStartOffset = vl.FirstDocumentLine.Offset; if (vlStartOffset > segmentEnd) break; int vlEndOffset = vl.LastDocumentLine.Offset + vl.LastDocumentLine.Length; if (vlEndOffset < segmentStart) continue; int segmentStartVc; if (segmentStart < vlStartOffset) segmentStartVc = 0; else segmentStartVc = vl.ValidateVisualColumn(start, extendToFullWidthAtLineEnd); int segmentEndVc; if (segmentEnd > vlEndOffset) segmentEndVc = extendToFullWidthAtLineEnd ? int.MaxValue : vl.VisualLengthWithEndOfLineMarker; else segmentEndVc = vl.ValidateVisualColumn(end, extendToFullWidthAtLineEnd); foreach (var rect in ProcessTextLines(textView, vl, segmentStartVc, segmentEndVc)) yield return rect; } } /// <summary> /// Calculates the rectangles for the visual column segment. /// This returns one rectangle for each line inside the segment. /// </summary> public static IEnumerable<Rect> GetRectsFromVisualSegment(TextView textView, VisualLine line, int startVc, int endVc) { if (textView == null) throw new ArgumentNullException("textView"); if (line == null) throw new ArgumentNullException("line"); return ProcessTextLines(textView, line, startVc, endVc); } private static IEnumerable<Rect> ProcessTextLines(TextView textView, VisualLine visualLine, int segmentStartVc, int segmentEndVc) { TextLine lastTextLine = visualLine.TextLines.Last(); Vector scrollOffset = textView.ScrollOffset; for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine) visualEndCol -= 1; // 1 position for the TextEndOfParagraph else visualEndCol -= line.TrailingWhitespaceLength; if (segmentEndVc < visualStartCol) break; if (lastTextLine != line && segmentStartVc > visualEndCol) continue; int segmentStartVcInLine = Math.Max(segmentStartVc, visualStartCol); int segmentEndVcInLine = Math.Min(segmentEndVc, visualEndCol); y -= scrollOffset.Y; Rect lastRect = Rect.Empty; if (segmentStartVcInLine == segmentEndVcInLine) { // GetTextBounds crashes for length=0, so we'll handle this case with GetDistanceFromCharacterHit // We need to return a rectangle to ensure empty lines are still visible double pos = visualLine.GetTextLineVisualXPosition(line, segmentStartVcInLine); pos -= scrollOffset.X; // The following special cases are necessary to get rid of empty rectangles at the end of a TextLine if "Show Spaces" is active. // If not excluded once, the same rectangle is calculated (and added) twice (since the offset could be mapped to two visual positions; end/start of line), if there is no trailing whitespace. // Skip this TextLine segment, if it is at the end of this line and this line is not the last line of the VisualLine and the selection continues and there is no trailing whitespace. if (segmentEndVcInLine == visualEndCol && i < visualLine.TextLines.Count - 1 && segmentEndVc > segmentEndVcInLine && line.TrailingWhitespaceLength == 0) continue; if (segmentStartVcInLine == visualStartCol && i > 0 && segmentStartVc < segmentStartVcInLine && visualLine.TextLines[i - 1].TrailingWhitespaceLength == 0) continue; lastRect = new Rect(pos, y, textView.EmptyLineSelectionWidth, line.Height); } else { if (segmentStartVcInLine <= visualEndCol) { foreach (var b in line.GetTextBounds(segmentStartVcInLine, segmentEndVcInLine - segmentStartVcInLine)) { double left = b.Rectangle.Left - scrollOffset.X; double right = b.Rectangle.Right - scrollOffset.X; if (!lastRect.IsEmpty) yield return lastRect; // left>right is possible in RTL languages lastRect = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); } } } // If the segment ends in virtual space, extend the last rectangle with the rectangle the portion of the selection // after the line end. // Also, when word-wrap is enabled and the segment continues into the next line, extend lastRect up to the end of the line. if (segmentEndVc > visualEndCol) { double left, right; if (segmentStartVc > visualLine.VisualLengthWithEndOfLineMarker) { // segmentStartVC is in virtual space left = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentStartVc); } else { // Otherwise, we already processed the rects from segmentStartVC up to visualEndCol, // so we only need to do the remainder starting at visualEndCol. // For word-wrapped lines, visualEndCol doesn't include the whitespace hidden by the wrap, // so we'll need to include it here. // For the last line, visualEndCol already includes the whitespace. left = (line == lastTextLine ? line.WidthIncludingTrailingWhitespace : line.Width); } if (line != lastTextLine || segmentEndVc == int.MaxValue) { // If word-wrap is enabled and the segment continues into the next line, // or if the extendToFullWidthAtLineEnd option is used (segmentEndVC == int.MaxValue), // we select the full width of the viewport. right = Math.Max(((ILogicalScrollable)textView).Extent.Width, ((ILogicalScrollable)textView).Viewport.Width); } else { right = visualLine.GetTextLineVisualXPosition(lastTextLine, segmentEndVc); } Rect extendSelection = new Rect(Math.Min(left, right), y, Math.Abs(right - left), line.Height); if (!lastRect.IsEmpty) { if (extendSelection.Intersects(lastRect)) { lastRect.Union(extendSelection); yield return lastRect; } else { // If the end of the line is in an RTL segment, keep lastRect and extendSelection separate. yield return lastRect; yield return extendSelection; } } else yield return extendSelection; } else yield return lastRect; } } private readonly PathFigures _figures = new PathFigures(); private PathFigure _figure; private int _insertionIndex; private double _lastTop, _lastBottom; private double _lastLeft, _lastRight; /// <summary> /// Adds a rectangle to the geometry. /// </summary> /// <remarks> /// This overload assumes that the coordinates are aligned properly /// (see <see cref="AlignToWholePixels"/>). /// Use the <see cref="AddRectangle(TextView,Rect)"/>-overload instead if the coordinates are not yet aligned. /// </remarks> public void AddRectangle(double left, double top, double right, double bottom) { if (!top.IsClose(_lastBottom)) { CloseFigure(); } if (_figure == null) { _figure = new PathFigure(); _figure.StartPoint = new Point(left, top + _cornerRadius); if (Math.Abs(left - right) > _cornerRadius) { _figure.Segments.Add(MakeArc(left + _cornerRadius, top, SweepDirection.Clockwise)); _figure.Segments.Add(MakeLineSegment(right - _cornerRadius, top)); _figure.Segments.Add(MakeArc(right, top + _cornerRadius, SweepDirection.Clockwise)); } _figure.Segments.Add(MakeLineSegment(right, bottom - _cornerRadius)); _insertionIndex = _figure.Segments.Count; //figure.Segments.Add(MakeArc(left, bottom - cornerRadius, SweepDirection.Clockwise)); } else { if (!_lastRight.IsClose(right)) { double cr = right < _lastRight ? -_cornerRadius : _cornerRadius; SweepDirection dir1 = right < _lastRight ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; SweepDirection dir2 = right < _lastRight ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; _figure.Segments.Insert(_insertionIndex++, MakeArc(_lastRight + cr, _lastBottom, dir1)); _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right - cr, top)); _figure.Segments.Insert(_insertionIndex++, MakeArc(right, top + _cornerRadius, dir2)); } _figure.Segments.Insert(_insertionIndex++, MakeLineSegment(right, bottom - _cornerRadius)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (!_lastLeft.IsClose(left)) { double cr = left < _lastLeft ? _cornerRadius : -_cornerRadius; SweepDirection dir1 = left < _lastLeft ? SweepDirection.CounterClockwise : SweepDirection.Clockwise; SweepDirection dir2 = left < _lastLeft ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, dir1)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft - cr, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(left + cr, _lastBottom, dir2)); } } this._lastTop = top; this._lastBottom = bottom; this._lastLeft = left; this._lastRight = right; } private ArcSegment MakeArc(double x, double y, SweepDirection dir) { var arc = new ArcSegment { Point = new Point(x, y), Size = new Size(CornerRadius, CornerRadius), SweepDirection = dir }; return arc; } private static LineSegment MakeLineSegment(double x, double y) { return new LineSegment { Point = new Point(x, y) }; } /// <summary> /// Closes the current figure. /// </summary> public void CloseFigure() { if (_figure != null) { _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft, _lastTop + _cornerRadius)); if (Math.Abs(_lastLeft - _lastRight) > _cornerRadius) { _figure.Segments.Insert(_insertionIndex, MakeArc(_lastLeft, _lastBottom - _cornerRadius, SweepDirection.Clockwise)); _figure.Segments.Insert(_insertionIndex, MakeLineSegment(_lastLeft + _cornerRadius, _lastBottom)); _figure.Segments.Insert(_insertionIndex, MakeArc(_lastRight - _cornerRadius, _lastBottom, SweepDirection.Clockwise)); } _figure.IsClosed = true; _figures.Add(_figure); _figure = null; } } /// <summary> /// Creates the geometry. /// Returns null when the geometry is empty! /// </summary> public Geometry CreateGeometry() { CloseFigure(); return _figures.Count != 0 ? new PathGeometry { Figures = _figures } : null; } } } <MSG> Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret Align the selection rectangle top position with the caret top position <DFF> @@ -196,7 +196,7 @@ namespace AvaloniaEdit.Rendering for (int i = 0; i < visualLine.TextLines.Count; i++) { TextLine line = visualLine.TextLines[i]; - double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.LineTop); + double y = visualLine.GetTextLineVisualYPosition(line, VisualYPosition.TextTop); int visualStartCol = visualLine.GetTextLineVisualStartColumn(line); int visualEndCol = visualStartCol + line.Length; if (line == lastTextLine)
1
Merge pull request #248 from AvaloniaUI/align-selection-rectangle-with-caret
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063172
<NME> jsgrid.validation.tests.js <BEF> ADDFILE <MSG> Core: Add validation feature Closes #12 Closes #176 <DFF> @@ -0,0 +1,279 @@ +$(function() { + + var validators = jsGrid.validators; + + + module("validation.validate", { + setup: function() { + this.validation = new jsGrid.Validation(); + } + }); + + test("as function", function() { + var validateFunction = function(value) { + return value === "test"; + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateFunction + }), [undefined]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateFunction + }), []); + }); + + test("as rule config", function() { + var validateRule = { + validator: function(value) { + return value === "test"; + }, + message: "Error" + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateRule + }), ["Error"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRule + }), []); + }); + + test("as rule config with param", function() { + var validateRule = { + validator: function(value, item, param) { + return value === param; + }, + param: "test", + message: "Error" + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateRule + }), ["Error"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRule + }), []); + }); + + test("as array of rules", function() { + var validateRules = [{ + message: "Error", + validator: function(value) { + return value !== ""; + } + }, { + validator: function(value) { + return value === "test"; + } + }]; + + deepEqual(this.validation.validate({ + value: "", + rules: validateRules + }), ["Error", undefined]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRules + }), []); + }); + + test("as string", function() { + validators.test_validator = function(value) { + return value === "test"; + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: "test_validator" + }), [undefined]); + + deepEqual(this.validation.validate({ + value: "test", + rules: "test_validator" + }), []); + + delete validators.test_validator; + }); + + test("as rule config with validator as string", function() { + validators.test_validator = function(value) { + return value === "test"; + }; + + var validateRule = { + validator: "test_validator", + message: "Error" + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateRule + }), ["Error"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRule + }), []); + + delete validators.test_validator; + }); + + test("as array of mixed rules", function() { + validators.test_validator = function(value) { + return value === "test"; + }; + + var validationRules = [ + "test_validator", + function(value) { + return value !== ""; + }, { + validator: function(value) { + return value === "test"; + }, + message: "Error" + } + ]; + + deepEqual(this.validation.validate({ + value: "", + rules: validationRules + }), [undefined, undefined, "Error"]); + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validationRules + }), [undefined, "Error"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validationRules + }), []); + + delete validators.test_validator; + }); + + test("as string validator with default error message", function() { + validators.test_validator = { + message: function(value) { + return "Error: " + value; + }, + validator: function(value) { + return value === "test"; + } + }; + + var validateRule = { + validator: "test_validator" + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateRule + }), ["Error: not_test"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRule + }), []); + + delete validators.test_validator; + }); + + test("throws exception for unknown validator", function() { + var validateRule = { + validator: "unknown_validator" + }; + + var validation = this.validation; + + throws(function() { + validation.validate({ + value: "test", + rules: validateRule + }); + }, /unknown validator "unknown_validator"/, "exception for unknown validator"); + }); + + + module("validators", { + setup: function() { + var validation = new jsGrid.Validation(); + + this.testValidator = function(validator, value, param) { + var result = validation.validate({ + value: value, + rules: { validator: validator, param: param } + }); + + return !result.length; + } + } + }); + + test("required", function() { + equal(this.testValidator("required", ""), false); + equal(this.testValidator("required", undefined), false); + equal(this.testValidator("required", null), false); + equal(this.testValidator("required", 0), true); + equal(this.testValidator("required", "test"), true); + }); + + test("rangeLength", function() { + equal(this.testValidator("rangeLength", "123456", [0, 5]), false); + equal(this.testValidator("rangeLength", "", [1, 5]), false); + equal(this.testValidator("rangeLength", "123", [0, 5]), true); + equal(this.testValidator("rangeLength", "", [0, 5]), true); + equal(this.testValidator("rangeLength", "12345", [0, 5]), true); + }); + + test("minLength", function() { + equal(this.testValidator("minLength", "123", 5), false); + equal(this.testValidator("minLength", "12345", 5), true); + equal(this.testValidator("minLength", "123456", 5), true); + }); + + test("maxLength", function() { + equal(this.testValidator("maxLength", "123456", 5), false); + equal(this.testValidator("maxLength", "12345", 5), true); + equal(this.testValidator("maxLength", "123", 5), true); + }); + + test("pattern", function() { + equal(this.testValidator("pattern", "_13_", "1?3"), false); + equal(this.testValidator("pattern", "13", "1?3"), true); + equal(this.testValidator("pattern", "3", "1?3"), true); + equal(this.testValidator("pattern", "_13_", /1?3/), true); + }); + + test("range", function() { + equal(this.testValidator("range", 6, [0, 5]), false); + equal(this.testValidator("range", 0, [1, 5]), false); + equal(this.testValidator("range", 3, [0, 5]), true); + equal(this.testValidator("range", 0, [0, 5]), true); + equal(this.testValidator("range", 5, [0, 5]), true); + }); + + test("min", function() { + equal(this.testValidator("min", 3, 5), false); + equal(this.testValidator("min", 5, 5), true); + equal(this.testValidator("min", 6, 5), true); + }); + + test("max", function() { + equal(this.testValidator("max", 6, 5), false); + equal(this.testValidator("max", 5, 5), true); + equal(this.testValidator("max", 3, 5), true); + }); + +});
279
Core: Add validation feature
0
.js
validation
mit
tabalinas/jsgrid
10063173
<NME> jsgrid.validation.tests.js <BEF> ADDFILE <MSG> Core: Add validation feature Closes #12 Closes #176 <DFF> @@ -0,0 +1,279 @@ +$(function() { + + var validators = jsGrid.validators; + + + module("validation.validate", { + setup: function() { + this.validation = new jsGrid.Validation(); + } + }); + + test("as function", function() { + var validateFunction = function(value) { + return value === "test"; + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateFunction + }), [undefined]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateFunction + }), []); + }); + + test("as rule config", function() { + var validateRule = { + validator: function(value) { + return value === "test"; + }, + message: "Error" + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateRule + }), ["Error"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRule + }), []); + }); + + test("as rule config with param", function() { + var validateRule = { + validator: function(value, item, param) { + return value === param; + }, + param: "test", + message: "Error" + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateRule + }), ["Error"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRule + }), []); + }); + + test("as array of rules", function() { + var validateRules = [{ + message: "Error", + validator: function(value) { + return value !== ""; + } + }, { + validator: function(value) { + return value === "test"; + } + }]; + + deepEqual(this.validation.validate({ + value: "", + rules: validateRules + }), ["Error", undefined]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRules + }), []); + }); + + test("as string", function() { + validators.test_validator = function(value) { + return value === "test"; + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: "test_validator" + }), [undefined]); + + deepEqual(this.validation.validate({ + value: "test", + rules: "test_validator" + }), []); + + delete validators.test_validator; + }); + + test("as rule config with validator as string", function() { + validators.test_validator = function(value) { + return value === "test"; + }; + + var validateRule = { + validator: "test_validator", + message: "Error" + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateRule + }), ["Error"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRule + }), []); + + delete validators.test_validator; + }); + + test("as array of mixed rules", function() { + validators.test_validator = function(value) { + return value === "test"; + }; + + var validationRules = [ + "test_validator", + function(value) { + return value !== ""; + }, { + validator: function(value) { + return value === "test"; + }, + message: "Error" + } + ]; + + deepEqual(this.validation.validate({ + value: "", + rules: validationRules + }), [undefined, undefined, "Error"]); + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validationRules + }), [undefined, "Error"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validationRules + }), []); + + delete validators.test_validator; + }); + + test("as string validator with default error message", function() { + validators.test_validator = { + message: function(value) { + return "Error: " + value; + }, + validator: function(value) { + return value === "test"; + } + }; + + var validateRule = { + validator: "test_validator" + }; + + deepEqual(this.validation.validate({ + value: "not_test", + rules: validateRule + }), ["Error: not_test"]); + + deepEqual(this.validation.validate({ + value: "test", + rules: validateRule + }), []); + + delete validators.test_validator; + }); + + test("throws exception for unknown validator", function() { + var validateRule = { + validator: "unknown_validator" + }; + + var validation = this.validation; + + throws(function() { + validation.validate({ + value: "test", + rules: validateRule + }); + }, /unknown validator "unknown_validator"/, "exception for unknown validator"); + }); + + + module("validators", { + setup: function() { + var validation = new jsGrid.Validation(); + + this.testValidator = function(validator, value, param) { + var result = validation.validate({ + value: value, + rules: { validator: validator, param: param } + }); + + return !result.length; + } + } + }); + + test("required", function() { + equal(this.testValidator("required", ""), false); + equal(this.testValidator("required", undefined), false); + equal(this.testValidator("required", null), false); + equal(this.testValidator("required", 0), true); + equal(this.testValidator("required", "test"), true); + }); + + test("rangeLength", function() { + equal(this.testValidator("rangeLength", "123456", [0, 5]), false); + equal(this.testValidator("rangeLength", "", [1, 5]), false); + equal(this.testValidator("rangeLength", "123", [0, 5]), true); + equal(this.testValidator("rangeLength", "", [0, 5]), true); + equal(this.testValidator("rangeLength", "12345", [0, 5]), true); + }); + + test("minLength", function() { + equal(this.testValidator("minLength", "123", 5), false); + equal(this.testValidator("minLength", "12345", 5), true); + equal(this.testValidator("minLength", "123456", 5), true); + }); + + test("maxLength", function() { + equal(this.testValidator("maxLength", "123456", 5), false); + equal(this.testValidator("maxLength", "12345", 5), true); + equal(this.testValidator("maxLength", "123", 5), true); + }); + + test("pattern", function() { + equal(this.testValidator("pattern", "_13_", "1?3"), false); + equal(this.testValidator("pattern", "13", "1?3"), true); + equal(this.testValidator("pattern", "3", "1?3"), true); + equal(this.testValidator("pattern", "_13_", /1?3/), true); + }); + + test("range", function() { + equal(this.testValidator("range", 6, [0, 5]), false); + equal(this.testValidator("range", 0, [1, 5]), false); + equal(this.testValidator("range", 3, [0, 5]), true); + equal(this.testValidator("range", 0, [0, 5]), true); + equal(this.testValidator("range", 5, [0, 5]), true); + }); + + test("min", function() { + equal(this.testValidator("min", 3, 5), false); + equal(this.testValidator("min", 5, 5), true); + equal(this.testValidator("min", 6, 5), true); + }); + + test("max", function() { + equal(this.testValidator("max", 6, 5), false); + equal(this.testValidator("max", 5, 5), true); + equal(this.testValidator("max", 3, 5), true); + }); + +});
279
Core: Add validation feature
0
.js
validation
mit
tabalinas/jsgrid
10063174
<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) ## Dependencies * PHP >= 5.5 * Lumen >= 5.3 ## Installation via Composer 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. 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> Merge pull request #2 from jmarcher/patch-2 updated min version of php <DFF> @@ -10,7 +10,7 @@ A simple service provider that makes Laravel Passport work with Lumen ## Dependencies -* PHP >= 5.5 +* PHP >= 5.6.3 * Lumen >= 5.3 ## Installation via Composer
1
Merge pull request #2 from jmarcher/patch-2
1
.md
md
mit
dusterio/lumen-passport
10063175
<NME> CODE_OF_CONDUCT.md <BEF> ADDFILE <MSG> Create CODE_OF_CONDUCT.md <DFF> @@ -0,0 +1,27 @@ +# Code of Conduct - Lumen Passport + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
27
Create CODE_OF_CONDUCT.md
0
.md
md
mit
dusterio/lumen-passport
10063176
<NME> jsgrid.validation.js <BEF> (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 long", validator: function(value, _, param) { return value.length >= param; } }, maxLength: { message: "Field value is too short", 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 large", validator: function(value, _, param) { return value >= param; } }, max: { message: "Field value is too small", validator: function(value, _, param) { return value <= param; } } }; jsGrid.validators = validators; }(jsGrid, jQuery)); <MSG> Validation: Fix messages for min/max and minLength/maxLength <DFF> @@ -85,14 +85,14 @@ }, minLength: { - message: "Field value is too long", + message: "Field value is too short", validator: function(value, _, param) { return value.length >= param; } }, maxLength: { - message: "Field value is too short", + message: "Field value is too long", validator: function(value, _, param) { return value.length <= param; } @@ -116,14 +116,14 @@ }, min: { - message: "Field value is too large", + message: "Field value is too small", validator: function(value, _, param) { return value >= param; } }, max: { - message: "Field value is too small", + message: "Field value is too large", validator: function(value, _, param) { return value <= param; }
4
Validation: Fix messages for min/max and minLength/maxLength
4
.js
validation
mit
tabalinas/jsgrid
10063177
<NME> jsgrid.validation.js <BEF> (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 long", validator: function(value, _, param) { return value.length >= param; } }, maxLength: { message: "Field value is too short", 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 large", validator: function(value, _, param) { return value >= param; } }, max: { message: "Field value is too small", validator: function(value, _, param) { return value <= param; } } }; jsGrid.validators = validators; }(jsGrid, jQuery)); <MSG> Validation: Fix messages for min/max and minLength/maxLength <DFF> @@ -85,14 +85,14 @@ }, minLength: { - message: "Field value is too long", + message: "Field value is too short", validator: function(value, _, param) { return value.length >= param; } }, maxLength: { - message: "Field value is too short", + message: "Field value is too long", validator: function(value, _, param) { return value.length <= param; } @@ -116,14 +116,14 @@ }, min: { - message: "Field value is too large", + message: "Field value is too small", validator: function(value, _, param) { return value >= param; } }, max: { - message: "Field value is too small", + message: "Field value is too large", validator: function(value, _, param) { return value <= param; }
4
Validation: Fix messages for min/max and minLength/maxLength
4
.js
validation
mit
tabalinas/jsgrid
10063178
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "field", name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Filtering: Method 'clearFilter' reloads data after filter row clearing <DFF> @@ -321,6 +321,11 @@ $(function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, + controller: { + loadData: function() { + return []; + } + }, fields: [ { name: "field",
5
Filtering: Method 'clearFilter' reloads data after filter row clearing
0
.js
tests
mit
tabalinas/jsgrid
10063179
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "field", name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Filtering: Method 'clearFilter' reloads data after filter row clearing <DFF> @@ -321,6 +321,11 @@ $(function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, + controller: { + loadData: function() { + return []; + } + }, fields: [ { name: "field",
5
Filtering: Method 'clearFilter' reloads data after filter row clearing
0
.js
tests
mit
tabalinas/jsgrid
10063180
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }); asyncTest("should support JS promise success callback", 1, function() { if(!Promise) { ok(true, "Promise not supported"); return; } module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" }); asyncTest("should support JS promise fail callback", 1, function() { if(!Promise) { ok(true, "Promise not supported"); return; } throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Tests: Fix check of standard Promise availability <DFF> @@ -2679,8 +2679,9 @@ $(function() { }); asyncTest("should support JS promise success callback", 1, function() { - if(!Promise) { + if(typeof Promise === "undefined") { ok(true, "Promise not supported"); + start(); return; } @@ -2708,8 +2709,9 @@ $(function() { }); asyncTest("should support JS promise fail callback", 1, function() { - if(!Promise) { + if(typeof Promise === "undefined") { ok(true, "Promise not supported"); + start(); return; }
4
Tests: Fix check of standard Promise availability
2
.js
tests
mit
tabalinas/jsgrid
10063181
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }); asyncTest("should support JS promise success callback", 1, function() { if(!Promise) { ok(true, "Promise not supported"); return; } module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" }); asyncTest("should support JS promise fail callback", 1, function() { if(!Promise) { ok(true, "Promise not supported"); return; } throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Tests: Fix check of standard Promise availability <DFF> @@ -2679,8 +2679,9 @@ $(function() { }); asyncTest("should support JS promise success callback", 1, function() { - if(!Promise) { + if(typeof Promise === "undefined") { ok(true, "Promise not supported"); + start(); return; } @@ -2708,8 +2709,9 @@ $(function() { }); asyncTest("should support JS promise fail callback", 1, function() { - if(!Promise) { + if(typeof Promise === "undefined") { ok(true, "Promise not supported"); + start(); return; }
4
Tests: Fix check of standard Promise availability
2
.js
tests
mit
tabalinas/jsgrid
10063182
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063183
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063184
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063185
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063186
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063187
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063188
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063189
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063190
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063191
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063192
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063193
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063194
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063195
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063196
<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 branch 'master' into dev <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 branch 'master' into dev
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063197
<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}}' RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] ``` ## License The MIT License (MIT) 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> @@ -201,6 +201,10 @@ RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] ``` +## Video tutorials + +I've just started a educational YouTube channel that will cover top IT trends in software development and DevOps: [config.sys](https://www.youtube.com/channel/UCIvUJ1iVRjJP_xL0CD7cMpg) + ## License The MIT License (MIT)
4
Update README.md
0
.md
md
mit
dusterio/lumen-passport
10063198
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); notEqual(grid.complexOption, gridOptions.complexOption, "object option copied"); deepEqual(grid.complexOption, gridOptions.complexOption, "object option copied correctly"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Extend non-primitive complex options <DFF> @@ -23,8 +23,7 @@ $(function() { equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); - notEqual(grid.complexOption, gridOptions.complexOption, "object option copied"); - deepEqual(grid.complexOption, gridOptions.complexOption, "object option copied correctly"); + equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() {
1
Core: Extend non-primitive complex options
2
.js
tests
mit
tabalinas/jsgrid
10063199
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); notEqual(grid.complexOption, gridOptions.complexOption, "object option copied"); deepEqual(grid.complexOption, gridOptions.complexOption, "object option copied correctly"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Extend non-primitive complex options <DFF> @@ -23,8 +23,7 @@ $(function() { equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); - notEqual(grid.complexOption, gridOptions.complexOption, "object option copied"); - deepEqual(grid.complexOption, gridOptions.complexOption, "object option copied correctly"); + equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() {
1
Core: Extend non-primitive complex options
2
.js
tests
mit
tabalinas/jsgrid
10063200
<NME> History.md <BEF> ADDFILE <MSG> Added History.md to log changes <DFF> @@ -0,0 +1,6 @@ +0.4.0 / 2013-05-17 +================== + + * change `slot` now defines placement over `id` + * change `children` can now be an object (keys as `slot`) or an array. + * change `id` is optional, used only for queries. \ No newline at end of file
6
Added History.md to log changes
0
.md
md
mit
ftlabs/fruitmachine
10063201
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063202
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063203
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063204
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063205
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063206
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063207
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063208
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063209
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063210
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063211
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063212
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063213
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063214
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063215
<NME> SearchPanel.xaml <BEF> <Styles xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> <Style Selector="ToggleButton.ExpanderToggle"> <Setter Property="Template"> <ControlTemplate> <Path Fill="Black" Data="M 0 2 L 4 6 L 0 10 Z" /> </ControlTemplate> </Setter> </Style> <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> <Setter Property="RenderTransform"> <ScaleTransform ScaleY="-1" /> </Setter> </Style> <Style Selector="search|SearchPanel"> <Setter Property="BorderThickness" Value="1" /> <Setter Property="BorderBrush" Value="DarkGray" /> <Setter Property="Background" Value="#eeeeee" /> <Setter Property="Template"> <ControlTemplate> <Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" HorizontalAlignment="Right" VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> <Grid ColumnDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto"> <ToggleButton Classes="ExpanderToggle" IsChecked="{TemplateBinding IsReplaceMode}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> </ToolTip.Tip> </ToggleButton> <TextBox Name="PART_searchTextBox" Grid.Column="1" Grid.Row="0" Width="150" Height="24" Margin="3,3,3,0" Text="{TemplateBinding SearchPattern}" /> <TextBox Name="ReplaceBox" IsVisible="{TemplateBinding IsSearchMode}" Grid.Column="1" Grid.Row="1" Width="150" Height="24" Margin="3 3 3 0" Text="{TemplateBinding ReplacePattern}" /> <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="0"> <search:DropDownButton Height="24"> <search:DropDownButton.DropDownContent> <Popup StaysOpen="False"> <Border BorderThickness="1"> <StackPanel Orientation="Vertical"> <CheckBox IsChecked="{TemplateBinding MatchCase}" Content="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding WholeWords}" Content="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" /> <CheckBox IsChecked="{TemplateBinding UseRegex}" Content="{x:Static ae:SR.SearchUseRegexText}" Margin="3" /> </StackPanel> </Border> </Popup> </search:DropDownButton.DropDownContent> </search:DropDownButton> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindPrevious}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.FindNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> </Button> <Button Height="16" Width="16" HorizontalAlignment="Right" VerticalAlignment="Top" Command="{x:Static search:SearchCommands.CloseSearchPanel}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Focusable="False"> <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" Stroke="Black" StrokeThickness="1" /> </Button> </StackPanel> <StackPanel Name="ReplaceButtons" IsVisible="{TemplateBinding IsSearchMode}" Orientation="Horizontal" Grid.Column="2" Grid.Row="1"> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceNext}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> </Button> <Button Margin="3" Height="24" Width="24" Command="{x:Static search:SearchCommands.ReplaceAll}"> <ToolTip.Tip> <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> </ToolTip.Tip> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> </Button> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> </StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" /> </ToggleButton> <ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3" Height="24" Width="24"> <Image Width="16" Height="16" Stretch="Fill" Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" /> </ToggleButton> </StackPanel> </StackPanel> </Grid> </Border> </ControlTemplate> </Setter> </Style> </Styles> <MSG> fix search panel layout. <DFF> @@ -3,158 +3,151 @@ xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit" xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit"> - <Style Selector="ToggleButton.ExpanderToggle"> - <Setter Property="Template"> - <ControlTemplate> - <Path Fill="Black" - Data="M 0 2 L 4 6 L 0 10 Z" /> - </ControlTemplate> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle"> + <Setter Property="Template"> + <ControlTemplate> + <Path Fill="Black" + VerticalAlignment="Center" + HorizontalAlignment="Center" + Data="M 0 2 L 4 6 L 0 10 Z" /> + </ControlTemplate> + </Setter> + </Style> - <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> - <Setter Property="RenderTransform"> - <ScaleTransform ScaleY="-1" /> - </Setter> - </Style> + <Style Selector="ToggleButton.ExpanderToggle:checked /template/ Path"> + + <Setter Property="RenderTransform"> + <RotateTransform Angle="90" /> + </Setter> + </Style> - <Style Selector="search|SearchPanel"> - <Setter Property="BorderThickness" - Value="1" /> - <Setter Property="BorderBrush" - Value="DarkGray" /> - <Setter Property="Background" - Value="#eeeeee" /> - <Setter Property="Template"> - <ControlTemplate> - <Border BorderThickness="{TemplateBinding BorderThickness}" - BorderBrush="{TemplateBinding BorderBrush}" - Background="{TemplateBinding Background}" - HorizontalAlignment="Right" - VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> - <Grid ColumnDefinitions="Auto,Auto,Auto" - RowDefinitions="Auto,Auto"> - <ToggleButton Classes="ExpanderToggle" - IsChecked="{TemplateBinding IsReplaceMode}" + <Style Selector="search|SearchPanel"> + <Setter Property="BorderThickness" + Value="1" /> + <Setter Property="BorderBrush" + Value="DarkGray" /> + <Setter Property="Background" + Value="#eeeeee" /> + <Setter Property="Template"> + <ControlTemplate> + <Border BorderThickness="{TemplateBinding BorderThickness}" + BorderBrush="{TemplateBinding BorderBrush}" + Background="{TemplateBinding Background}" + HorizontalAlignment="Right" + VerticalAlignment="Top" TextBlock.FontFamily="Segoi UI" TextBlock.FontSize="10"> + <Grid ColumnDefinitions="Auto,Auto,Auto" + RowDefinitions="Auto,Auto"> + <ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" + IsChecked="{TemplateBinding IsReplaceMode, Mode=TwoWay}" Grid.Column="0" Grid.Row="0" Width="16" Margin="2"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> - </ToolTip.Tip> - </ToggleButton> - - <TextBox Name="PART_searchTextBox" - Grid.Column="1" - Grid.Row="0" - Width="150" - Height="24" - Margin="3,3,3,0" - Text="{TemplateBinding SearchPattern}" /> - - <TextBox Name="ReplaceBox" - IsVisible="{TemplateBinding IsSearchMode}" - Grid.Column="1" - Grid.Row="1" - Width="150" - Height="24" - Margin="3 3 3 0" - Text="{TemplateBinding ReplacePattern}" /> - - <StackPanel Orientation="Horizontal" - Grid.Column="2" - Grid.Row="0"> - <search:DropDownButton Height="24"> - <search:DropDownButton.DropDownContent> - <Popup StaysOpen="False"> - <Border BorderThickness="1"> - <StackPanel Orientation="Vertical"> - <CheckBox IsChecked="{TemplateBinding MatchCase}" - Content="{x:Static ae:SR.SearchMatchCaseText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding WholeWords}" - Content="{x:Static ae:SR.SearchMatchWholeWordsText}" - Margin="3" /> - <CheckBox IsChecked="{TemplateBinding UseRegex}" - Content="{x:Static ae:SR.SearchUseRegexText}" - Margin="3" /> - </StackPanel> - </Border> - </Popup> - </search:DropDownButton.DropDownContent> - </search:DropDownButton> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindPrevious}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.FindNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Height="16" - Width="16" - HorizontalAlignment="Right" - VerticalAlignment="Top" - Command="{x:Static search:SearchCommands.CloseSearchPanel}" - VerticalContentAlignment="Center" - HorizontalContentAlignment="Center" - Focusable="False"> - <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" - Stroke="Black" - StrokeThickness="1" /> - </Button> - </StackPanel> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" /> + </ToolTip.Tip> + </ToggleButton> + <StackPanel Grid.Column="1"> + <StackPanel Orientation="Horizontal" + Grid.Column="2" + Grid.Row="0"> + <TextBox Name="PART_searchTextBox" + Grid.Column="1" + Grid.Row="0" + Width="150" + Height="24" + Margin="3,3,3,0" + Text="{TemplateBinding SearchPattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindPrevious}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.FindNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchFindNextText}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Height="16" + Width="16" + HorizontalAlignment="Right" + VerticalAlignment="Top" + Command="{x:Static search:SearchCommands.CloseSearchPanel}" + VerticalContentAlignment="Center" + HorizontalContentAlignment="Center" + Focusable="False"> + <Path Data="M 0,0 L 8,8 M 8,0 L 0,8" + Stroke="Black" + StrokeThickness="1" /> + </Button> + </StackPanel> - <StackPanel Name="ReplaceButtons" - IsVisible="{TemplateBinding IsSearchMode}" - Orientation="Horizontal" - Grid.Column="2" - Grid.Row="1"> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceNext}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> - </Button> - <Button Margin="3" - Height="24" - Width="24" - Command="{x:Static search:SearchCommands.ReplaceAll}"> - <ToolTip.Tip> - <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> - </ToolTip.Tip> - <Image Width="16" - Height="16" - Stretch="Fill" - Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> - </Button> - </StackPanel> - </Grid> - </Border> - </ControlTemplate> - </Setter> - </Style> + <StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}" + Orientation="Horizontal" + Grid.Column="2" + Grid.Row="1"> + <TextBox Name="ReplaceBox" + IsVisible="{TemplateBinding IsSearchMode}" + Grid.Column="1" + Grid.Row="1" + Width="150" + Height="24" + Margin="3 3 3 0" + Text="{TemplateBinding ReplacePattern}" /> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceNext}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" /> + </Button> + <Button Margin="3" + Height="24" + Width="24" + Command="{x:Static search:SearchCommands.ReplaceAll}"> + <ToolTip.Tip> + <TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" /> + </ToolTip.Tip> + <Image Width="16" + Height="16" + Stretch="Fill" + Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" /> + </Button> + </StackPanel> + <StackPanel Orientation="Horizontal"> + <CheckBox IsChecked="{TemplateBinding MatchCase}" + Content="{x:Static ae:SR.SearchMatchCaseText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding WholeWords}" + Content="{x:Static ae:SR.SearchMatchWholeWordsText}" + Margin="3" /> + <CheckBox IsChecked="{TemplateBinding UseRegex}" + Content="{x:Static ae:SR.SearchUseRegexText}" + Margin="3" /> + </StackPanel> + </StackPanel> + </Grid> + </Border> + </ControlTemplate> + </Setter> + </Style> </Styles> \ No newline at end of file
140
fix search panel layout.
147
.xaml
xaml
mit
AvaloniaUI/AvaloniaEdit
10063216
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063217
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063218
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063219
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063220
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063221
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063222
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063223
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063224
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063225
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063226
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063227
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063228
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063229
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063230
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> <Version>0.10.0-preview6</Version> </PropertyGroup> <ItemGroup> <EmbeddedResource Include="**\*.xshd;**\*.resx;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> update avalonia. <DFF> @@ -3,7 +3,7 @@ <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>612,618</WarningsNotAsErrors> - <Version>0.10.0-preview6</Version> + <Version>0.10.0-rc1</Version> </PropertyGroup> <ItemGroup>
1
update avalonia.
1
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10063231
<NME> jsgrid.core.js <BEF> (function(window, $, undefined) { var JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID, JSGRID_ROW_DATA_KEY = "JSGridItem", JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", SORT_ORDER_ASC = "asc", SORT_ORDER_DESC = "desc", FIRST_PAGE_PLACEHOLDER = "{first}", PAGES_PLACEHOLDER = "{pages}", PREV_PAGE_PLACEHOLDER = "{prev}", NEXT_PAGE_PLACEHOLDER = "{next}", LAST_PAGE_PLACEHOLDER = "{last}", PAGE_INDEX_PLACEHOLDER = "{pageIndex}", PAGE_COUNT_PLACEHOLDER = "{pageCount}", ITEM_COUNT_PLACEHOLDER = "{itemCount}", EMPTY_HREF = "javascript:void(0);"; var getOrApply = function(value, context) { if($.isFunction(value)) { 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, editRowClass: "jsgrid-edit-row", confirmDeleting: true, deleteConfirmMessage: "Are you sure?", deleteConfirm: function(item) { return this.deleteConfirmMessage; }, selecting: true, selectedRowClass: "jsgrid-selected-row", 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, insertRowLocation: "bottom", 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, onItemEditCancelling: $.noop, onItemUpdating: $.noop, onItemUpdated: $.noop, onItemInvalid: $.noop, onDataLoading: $.noop, onDataLoaded: $.noop, onDataExporting: $.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) { var 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) { var self = this; self.data.sort(function(item1, item2) { var value1 = self._getItemFieldValue(item1, sortField); var value2 = self._getItemFieldValue(item2, sortField); return sortFactor * sortField.sortingFunc(value1, value2); }); } }, _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(), itemCount = this._itemsCount(), pagerParts = this.pagerFormat.split(" "); return $.map(pagerParts, $.proxy(function(pagerPart) { var result = pagerPart; if(pagerPart === PAGES_PLACEHOLDER) { result = this._createPages(); } 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; } return $.isArray(result) ? result.concat([" "]) : [result, " "]; }, this)); }, _createPages: function() { var pageCount = this._pagesCount(), pageButtonCount = this.pageButtonCount, firstDisplayingPage = this._firstDisplayingPage, pages = []; 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 }); }); }, exportData: function(exportOptions){ var options = exportOptions || {}; var type = options.type || "csv"; var result = ""; this._callEventHandler(this.onDataExporting); switch(type){ case "csv": if(!$row.length) return; if(this.confirmDeleting && !window.confirm(this.deleteConfirm($row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); _dataToCsv: function(options){ var options = options || {}; var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true; var subset = options.subset || "all"; var filter = options.filter || undefined; var result = []; if (includeHeaders){ var fieldsLength = this.fields.length; var fieldNames = {}; for(var i=0;i<fieldsLength;i++){ var field = this.fields[i]; if ("includeInDataExport" in field){ if (field.includeInDataExport === true) fieldNames[i] = field.title || field.name; } } var headerLine = this._itemToCsv(fieldNames,{},options); result.push(headerLine); } var exportStartIndex = 0; var exportEndIndex = this.data.length; switch(subset){ case "visible": exportEndIndex = this._firstDisplayingPage * this.pageSize; exportStartIndex = exportEndIndex - this.pageSize; case "all": default: break; } for (var i = exportStartIndex; i < exportEndIndex; i++){ var item = this.data[i]; var itemLine = ""; var includeItem = true; if (filter) if (!filter(item)) includeItem = false; if (includeItem){ itemLine = this._itemToCsv(item, this.fields, options); result.push(itemLine); } } return result.join(""); }, _itemToCsv: function(item, fields, options){ var options = options || {}; var delimiter = options.delimiter || "|"; var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true; var newline = options.newline || "\r\n"; var transforms = options.transforms || {}; var fields = fields || {}; var getItem = this._getItemFieldValue; var result = []; Object.keys(item).forEach(function(key,index) { var entry = ""; //Fields.length is greater than 0 when we are matching agaisnt fields //Field.length will be 0 when exporting header rows if (fields.length > 0){ var field = fields[index]; //Field may be excluded from data export if ("includeInDataExport" in field){ if (field.includeInDataExport){ //Field may be a select, which requires additional logic if (field.type === "select"){ var selectedItem = getItem(item, field); var resultItem = $.grep(field.items, function(item, index) { return item[field.valueField] === selectedItem; })[0] || ""; entry = resultItem[field.textField]; } else{ entry = getItem(item, field); } } else{ return; } } else{ entry = getItem(item, field); } if (transforms.hasOwnProperty(field.name)){ entry = transforms[field.name](entry); } } else{ entry = item[key]; } if (encapsulate){ entry = '"'+entry+'"'; } result.push(entry); }); return result.join(delimiter) + newline; }, getFilter: function() { var result = {}; this._eachField(function(field) { if(field.filtering) { this._setItemFieldValue(result, field, field.filterValue()); } }); return result; }, _sortingParams: function() { if(this.sorting && this._sortField) { return { sortField: this._sortField.name, sortOrder: this._sortOrder }; } return {}; }, getSorting: function() { var sortingParams = this._sortingParams(); return { field: sortingParams.sortField, order: sortingParams.sortOrder }; }, clearFilter: function() { var $filterRow = this._createFilterRow(); this._filterRow.replaceWith($filterRow); this._filterRow = $filterRow; return this.search(); }, insertItem: function(item) { var insertingItem = item || this._getValidatedInsertItem(); if(!insertingItem) return $.Deferred().reject().promise(); var args = this._callEventHandler(this.onItemInserting, { item: insertingItem }); return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) { insertedItem = insertedItem || insertingItem; this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation); this._callEventHandler(this.onItemInserted, { item: insertedItem }); }); }, _getValidatedInsertItem: function() { var item = this._getInsertItem(); return this._validateItem(item, this._insertRow) ? item : null; }, _getInsertItem: function() { var result = {}; this._eachField(function(field) { if(field.inserting) { this._setItemFieldValue(result, field, field.insertValue()); } }); return result; }, _validateItem: function(item, $row) { var validationErrors = []; var args = { item: item, itemIndex: this._rowIndex($row), row: $row }; this._eachField(function(field) { if(!field.validate || ($row === this._insertRow && !field.inserting) || ($row === this._getEditRow() && !field.editing)) return; var fieldValue = this._getItemFieldValue(item, field); var errors = this._validation.validate($.extend({ value: fieldValue, rules: field.validate }, args)); this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors); if(!errors.length) return; validationErrors.push.apply(validationErrors, $.map(errors, function(message) { return { field: field, message: message }; })); }); if(!validationErrors.length) return true; var invalidArgs = $.extend({ errors: validationErrors }, args); this._callEventHandler(this.onItemInvalid, invalidArgs); this.invalidNotify(invalidArgs); return false; }, _setCellValidity: function($cell, errors) { $cell .toggleClass(this.invalidClass, !!errors.length) .attr("title", errors.join("\n")); }, clearInsert: function() { var insertRow = this._createInsertRow(); this._insertRow.replaceWith(insertRow); this._insertRow = insertRow; this.refresh(); }, editItem: function(item) { var $row = this.rowByItem(item); if($row.length) { this._editRow($row); } }, rowByItem: function(item) { if(item.jquery || item.nodeType) return $(item); return this._content.find("tr").filter(function() { return $.data(this, JSGRID_ROW_DATA_KEY) === item; }); }, _editRow: function($row) { if(!this.editing) return; var item = $row.data(JSGRID_ROW_DATA_KEY); var args = this._callEventHandler(this.onItemEditing, { row: $row, item: item, itemIndex: this._itemIndex(item) }); if(args.cancel) return; if(this._editingRow) { this.cancelEdit(); } var $editRow = this._createEditRow(item); this._editingRow = $row; $row.hide(); $editRow.insertBefore($row); $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); }, _createEditRow: function(item) { if($.isFunction(this.editRowRenderer)) { return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) })); } var $result = $("<tr>").addClass(this.editRowClass); this._eachField(function(field) { var fieldValue = this._getItemFieldValue(item, field); this._prepareCell("<td>", field, "editcss") .append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item })) .appendTo($result); }); return $result; }, updateItem: function(item, editedItem) { if(arguments.length === 1) { editedItem = item; } var $row = item ? this.rowByItem(item) : this._editingRow; editedItem = editedItem || this._getValidatedEditedItem(); if(!editedItem) return; return this._updateRow($row, editedItem); }, _getValidatedEditedItem: function() { var item = this._getEditedItem(); return this._validateItem(item, this._getEditRow()) ? item : null; }, _updateRow: function($updatingRow, editedItem) { var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), updatingItemIndex = this._itemIndex(updatingItem), updatedItem = $.extend(true, {}, updatingItem, editedItem); var args = this._callEventHandler(this.onItemUpdating, { row: $updatingRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: updatingItem }); return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) { var previousItem = $.extend(true, {}, updatingItem); updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem); var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); this._callEventHandler(this.onItemUpdated, { row: $updatedRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: previousItem }); }); }, _rowIndex: function(row) { return this._content.children().index($(row)); }, _itemIndex: function(item) { return $.inArray(item, this.data); }, _finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) { this.cancelEdit(); this.data[updatedItemIndex] = updatedItem; var $updatedRow = this._createRow(updatedItem, updatedItemIndex); $updatingRow.replaceWith($updatedRow); return $updatedRow; }, _getEditedItem: function() { var result = {}; this._eachField(function(field) { if(field.editing) { this._setItemFieldValue(result, field, field.editValue()); } }); return result; }, cancelEdit: function() { if(!this._editingRow) return; var $row = this._editingRow, editingItem = $row.data(JSGRID_ROW_DATA_KEY), editingItemIndex = this._itemIndex(editingItem); this._callEventHandler(this.onItemEditCancelling, { row: $row, item: editingItem, itemIndex: editingItemIndex }); this._getEditRow().remove(); this._editingRow.show(); this._editingRow = null; }, _getEditRow: function() { return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY); }, deleteItem: function(item) { var $row = this.rowByItem(item); if(!$row.length) return; if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); }, _deleteRow: function($row) { var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), deletingItemIndex = this._itemIndex(deletingItem); var args = this._callEventHandler(this.onItemDeleting, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); return this._controllerCall("deleteItem", deletingItem, args.cancel, function() { this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); this._callEventHandler(this.onItemDeleted, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); }); } }; $.fn.jsGrid = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSGRID_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance.render(); } } else { new Grid($element, config); } }); return result; }; var fields = {}; var setDefaults = function(config) { var componentPrototype; if($.isPlainObject(config)) { componentPrototype = Grid.prototype; } else { componentPrototype = fields[config].prototype; config = arguments[1] || {}; } $.extend(componentPrototype, config); }; var locales = {}; var locale = function(lang) { var localeConfig = $.isPlainObject(lang) ? lang : locales[lang]; if(!localeConfig) throw Error("unknown locale " + lang); setLocale(jsGrid, localeConfig); }; var setLocale = function(obj, localeConfig) { $.each(localeConfig, function(field, value) { if($.isPlainObject(value)) { setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value); return; } if(obj.hasOwnProperty(field)) { obj[field] = value; } else { obj.prototype[field] = value; } }); }; window.jsGrid = { Grid: Grid, fields: fields, setDefaults: setDefaults, locales: locales, locale: locale, version: "@VERSION" }; }(window, jQuery)); <MSG> Core: Merge deleteConfirmMessage with deleteConfirm options <DFF> @@ -79,10 +79,7 @@ editRowClass: "jsgrid-edit-row", confirmDeleting: true, - deleteConfirmMessage: "Are you sure?", - deleteConfirm: function(item) { - return this.deleteConfirmMessage; - }, + deleteConfirm: "Are you sure?", selecting: true, selectedRowClass: "jsgrid-selected-row", @@ -1098,7 +1095,7 @@ if(!$row.length) return; - if(this.confirmDeleting && !window.confirm(this.deleteConfirm($row.data(JSGRID_ROW_DATA_KEY)))) + if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row);
2
Core: Merge deleteConfirmMessage with deleteConfirm options
5
.js
core
mit
tabalinas/jsgrid
10063232
<NME> jsgrid.core.js <BEF> (function(window, $, undefined) { var JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID, JSGRID_ROW_DATA_KEY = "JSGridItem", JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow", SORT_ORDER_ASC = "asc", SORT_ORDER_DESC = "desc", FIRST_PAGE_PLACEHOLDER = "{first}", PAGES_PLACEHOLDER = "{pages}", PREV_PAGE_PLACEHOLDER = "{prev}", NEXT_PAGE_PLACEHOLDER = "{next}", LAST_PAGE_PLACEHOLDER = "{last}", PAGE_INDEX_PLACEHOLDER = "{pageIndex}", PAGE_COUNT_PLACEHOLDER = "{pageCount}", ITEM_COUNT_PLACEHOLDER = "{itemCount}", EMPTY_HREF = "javascript:void(0);"; var getOrApply = function(value, context) { if($.isFunction(value)) { 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, editRowClass: "jsgrid-edit-row", confirmDeleting: true, deleteConfirmMessage: "Are you sure?", deleteConfirm: function(item) { return this.deleteConfirmMessage; }, selecting: true, selectedRowClass: "jsgrid-selected-row", 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, insertRowLocation: "bottom", 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, onItemEditCancelling: $.noop, onItemUpdating: $.noop, onItemUpdated: $.noop, onItemInvalid: $.noop, onDataLoading: $.noop, onDataLoaded: $.noop, onDataExporting: $.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) { var 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) { var self = this; self.data.sort(function(item1, item2) { var value1 = self._getItemFieldValue(item1, sortField); var value2 = self._getItemFieldValue(item2, sortField); return sortFactor * sortField.sortingFunc(value1, value2); }); } }, _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(), itemCount = this._itemsCount(), pagerParts = this.pagerFormat.split(" "); return $.map(pagerParts, $.proxy(function(pagerPart) { var result = pagerPart; if(pagerPart === PAGES_PLACEHOLDER) { result = this._createPages(); } 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; } return $.isArray(result) ? result.concat([" "]) : [result, " "]; }, this)); }, _createPages: function() { var pageCount = this._pagesCount(), pageButtonCount = this.pageButtonCount, firstDisplayingPage = this._firstDisplayingPage, pages = []; 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 }); }); }, exportData: function(exportOptions){ var options = exportOptions || {}; var type = options.type || "csv"; var result = ""; this._callEventHandler(this.onDataExporting); switch(type){ case "csv": if(!$row.length) return; if(this.confirmDeleting && !window.confirm(this.deleteConfirm($row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); _dataToCsv: function(options){ var options = options || {}; var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true; var subset = options.subset || "all"; var filter = options.filter || undefined; var result = []; if (includeHeaders){ var fieldsLength = this.fields.length; var fieldNames = {}; for(var i=0;i<fieldsLength;i++){ var field = this.fields[i]; if ("includeInDataExport" in field){ if (field.includeInDataExport === true) fieldNames[i] = field.title || field.name; } } var headerLine = this._itemToCsv(fieldNames,{},options); result.push(headerLine); } var exportStartIndex = 0; var exportEndIndex = this.data.length; switch(subset){ case "visible": exportEndIndex = this._firstDisplayingPage * this.pageSize; exportStartIndex = exportEndIndex - this.pageSize; case "all": default: break; } for (var i = exportStartIndex; i < exportEndIndex; i++){ var item = this.data[i]; var itemLine = ""; var includeItem = true; if (filter) if (!filter(item)) includeItem = false; if (includeItem){ itemLine = this._itemToCsv(item, this.fields, options); result.push(itemLine); } } return result.join(""); }, _itemToCsv: function(item, fields, options){ var options = options || {}; var delimiter = options.delimiter || "|"; var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true; var newline = options.newline || "\r\n"; var transforms = options.transforms || {}; var fields = fields || {}; var getItem = this._getItemFieldValue; var result = []; Object.keys(item).forEach(function(key,index) { var entry = ""; //Fields.length is greater than 0 when we are matching agaisnt fields //Field.length will be 0 when exporting header rows if (fields.length > 0){ var field = fields[index]; //Field may be excluded from data export if ("includeInDataExport" in field){ if (field.includeInDataExport){ //Field may be a select, which requires additional logic if (field.type === "select"){ var selectedItem = getItem(item, field); var resultItem = $.grep(field.items, function(item, index) { return item[field.valueField] === selectedItem; })[0] || ""; entry = resultItem[field.textField]; } else{ entry = getItem(item, field); } } else{ return; } } else{ entry = getItem(item, field); } if (transforms.hasOwnProperty(field.name)){ entry = transforms[field.name](entry); } } else{ entry = item[key]; } if (encapsulate){ entry = '"'+entry+'"'; } result.push(entry); }); return result.join(delimiter) + newline; }, getFilter: function() { var result = {}; this._eachField(function(field) { if(field.filtering) { this._setItemFieldValue(result, field, field.filterValue()); } }); return result; }, _sortingParams: function() { if(this.sorting && this._sortField) { return { sortField: this._sortField.name, sortOrder: this._sortOrder }; } return {}; }, getSorting: function() { var sortingParams = this._sortingParams(); return { field: sortingParams.sortField, order: sortingParams.sortOrder }; }, clearFilter: function() { var $filterRow = this._createFilterRow(); this._filterRow.replaceWith($filterRow); this._filterRow = $filterRow; return this.search(); }, insertItem: function(item) { var insertingItem = item || this._getValidatedInsertItem(); if(!insertingItem) return $.Deferred().reject().promise(); var args = this._callEventHandler(this.onItemInserting, { item: insertingItem }); return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) { insertedItem = insertedItem || insertingItem; this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation); this._callEventHandler(this.onItemInserted, { item: insertedItem }); }); }, _getValidatedInsertItem: function() { var item = this._getInsertItem(); return this._validateItem(item, this._insertRow) ? item : null; }, _getInsertItem: function() { var result = {}; this._eachField(function(field) { if(field.inserting) { this._setItemFieldValue(result, field, field.insertValue()); } }); return result; }, _validateItem: function(item, $row) { var validationErrors = []; var args = { item: item, itemIndex: this._rowIndex($row), row: $row }; this._eachField(function(field) { if(!field.validate || ($row === this._insertRow && !field.inserting) || ($row === this._getEditRow() && !field.editing)) return; var fieldValue = this._getItemFieldValue(item, field); var errors = this._validation.validate($.extend({ value: fieldValue, rules: field.validate }, args)); this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors); if(!errors.length) return; validationErrors.push.apply(validationErrors, $.map(errors, function(message) { return { field: field, message: message }; })); }); if(!validationErrors.length) return true; var invalidArgs = $.extend({ errors: validationErrors }, args); this._callEventHandler(this.onItemInvalid, invalidArgs); this.invalidNotify(invalidArgs); return false; }, _setCellValidity: function($cell, errors) { $cell .toggleClass(this.invalidClass, !!errors.length) .attr("title", errors.join("\n")); }, clearInsert: function() { var insertRow = this._createInsertRow(); this._insertRow.replaceWith(insertRow); this._insertRow = insertRow; this.refresh(); }, editItem: function(item) { var $row = this.rowByItem(item); if($row.length) { this._editRow($row); } }, rowByItem: function(item) { if(item.jquery || item.nodeType) return $(item); return this._content.find("tr").filter(function() { return $.data(this, JSGRID_ROW_DATA_KEY) === item; }); }, _editRow: function($row) { if(!this.editing) return; var item = $row.data(JSGRID_ROW_DATA_KEY); var args = this._callEventHandler(this.onItemEditing, { row: $row, item: item, itemIndex: this._itemIndex(item) }); if(args.cancel) return; if(this._editingRow) { this.cancelEdit(); } var $editRow = this._createEditRow(item); this._editingRow = $row; $row.hide(); $editRow.insertBefore($row); $row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow); }, _createEditRow: function(item) { if($.isFunction(this.editRowRenderer)) { return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) })); } var $result = $("<tr>").addClass(this.editRowClass); this._eachField(function(field) { var fieldValue = this._getItemFieldValue(item, field); this._prepareCell("<td>", field, "editcss") .append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item })) .appendTo($result); }); return $result; }, updateItem: function(item, editedItem) { if(arguments.length === 1) { editedItem = item; } var $row = item ? this.rowByItem(item) : this._editingRow; editedItem = editedItem || this._getValidatedEditedItem(); if(!editedItem) return; return this._updateRow($row, editedItem); }, _getValidatedEditedItem: function() { var item = this._getEditedItem(); return this._validateItem(item, this._getEditRow()) ? item : null; }, _updateRow: function($updatingRow, editedItem) { var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY), updatingItemIndex = this._itemIndex(updatingItem), updatedItem = $.extend(true, {}, updatingItem, editedItem); var args = this._callEventHandler(this.onItemUpdating, { row: $updatingRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: updatingItem }); return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) { var previousItem = $.extend(true, {}, updatingItem); updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem); var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex); this._callEventHandler(this.onItemUpdated, { row: $updatedRow, item: updatedItem, itemIndex: updatingItemIndex, previousItem: previousItem }); }); }, _rowIndex: function(row) { return this._content.children().index($(row)); }, _itemIndex: function(item) { return $.inArray(item, this.data); }, _finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) { this.cancelEdit(); this.data[updatedItemIndex] = updatedItem; var $updatedRow = this._createRow(updatedItem, updatedItemIndex); $updatingRow.replaceWith($updatedRow); return $updatedRow; }, _getEditedItem: function() { var result = {}; this._eachField(function(field) { if(field.editing) { this._setItemFieldValue(result, field, field.editValue()); } }); return result; }, cancelEdit: function() { if(!this._editingRow) return; var $row = this._editingRow, editingItem = $row.data(JSGRID_ROW_DATA_KEY), editingItemIndex = this._itemIndex(editingItem); this._callEventHandler(this.onItemEditCancelling, { row: $row, item: editingItem, itemIndex: editingItemIndex }); this._getEditRow().remove(); this._editingRow.show(); this._editingRow = null; }, _getEditRow: function() { return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY); }, deleteItem: function(item) { var $row = this.rowByItem(item); if(!$row.length) return; if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row); }, _deleteRow: function($row) { var deletingItem = $row.data(JSGRID_ROW_DATA_KEY), deletingItemIndex = this._itemIndex(deletingItem); var args = this._callEventHandler(this.onItemDeleting, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); return this._controllerCall("deleteItem", deletingItem, args.cancel, function() { this._loadStrategy.finishDelete(deletingItem, deletingItemIndex); this._callEventHandler(this.onItemDeleted, { row: $row, item: deletingItem, itemIndex: deletingItemIndex }); }); } }; $.fn.jsGrid = function(config) { var args = $.makeArray(arguments), methodArgs = args.slice(1), result = this; this.each(function() { var $element = $(this), instance = $element.data(JSGRID_DATA_KEY), methodResult; if(instance) { if(typeof config === "string") { methodResult = instance[config].apply(instance, methodArgs); if(methodResult !== undefined && methodResult !== instance) { result = methodResult; return false; } } else { instance._detachWindowResizeCallback(); instance._init(config); instance.render(); } } else { new Grid($element, config); } }); return result; }; var fields = {}; var setDefaults = function(config) { var componentPrototype; if($.isPlainObject(config)) { componentPrototype = Grid.prototype; } else { componentPrototype = fields[config].prototype; config = arguments[1] || {}; } $.extend(componentPrototype, config); }; var locales = {}; var locale = function(lang) { var localeConfig = $.isPlainObject(lang) ? lang : locales[lang]; if(!localeConfig) throw Error("unknown locale " + lang); setLocale(jsGrid, localeConfig); }; var setLocale = function(obj, localeConfig) { $.each(localeConfig, function(field, value) { if($.isPlainObject(value)) { setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value); return; } if(obj.hasOwnProperty(field)) { obj[field] = value; } else { obj.prototype[field] = value; } }); }; window.jsGrid = { Grid: Grid, fields: fields, setDefaults: setDefaults, locales: locales, locale: locale, version: "@VERSION" }; }(window, jQuery)); <MSG> Core: Merge deleteConfirmMessage with deleteConfirm options <DFF> @@ -79,10 +79,7 @@ editRowClass: "jsgrid-edit-row", confirmDeleting: true, - deleteConfirmMessage: "Are you sure?", - deleteConfirm: function(item) { - return this.deleteConfirmMessage; - }, + deleteConfirm: "Are you sure?", selecting: true, selectedRowClass: "jsgrid-selected-row", @@ -1098,7 +1095,7 @@ if(!$row.length) return; - if(this.confirmDeleting && !window.confirm(this.deleteConfirm($row.data(JSGRID_ROW_DATA_KEY)))) + if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY)))) return; return this._deleteRow($row);
2
Core: Merge deleteConfirmMessage with deleteConfirm options
5
.js
core
mit
tabalinas/jsgrid
10063233
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063234
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063235
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063236
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063237
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063238
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063239
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063240
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063241
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063242
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063243
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063244
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063245
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063246
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063247
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; { base.Show(); } } public new void Hide() #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> fix black border + window hiding <DFF> @@ -126,6 +126,8 @@ namespace AvaloniaEdit.CodeCompletion { base.Show(); } + Height = double.NaN; + MinHeight = 0; } public new void Hide()
2
fix black border + window hiding
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10063248
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project> <MSG> Upgrade to TextMateSharp 1.0.14 <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.13" /> + <PackageReference Include="TextMateSharp" Version="1.0.14" /> </ItemGroup> </Project>
1
Upgrade to TextMateSharp 1.0.14
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10063249
<NME> AvaloniaEdit.TextMate.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>latest</LangVersion> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="TextMateSharp" Version="$(TextMateSharpVersion)" /> <PackageReference Include="TextMateSharp.Grammars" Version="$(TextMateSharpVersion)" /> </ItemGroup> </Project> <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="TextMateSharp" Version="1.0.13" /> </ItemGroup> </Project> <MSG> Upgrade to TextMateSharp 1.0.14 <DFF> @@ -19,7 +19,7 @@ <ItemGroup> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> - <PackageReference Include="TextMateSharp" Version="1.0.13" /> + <PackageReference Include="TextMateSharp" Version="1.0.14" /> </ItemGroup> </Project>
1
Upgrade to TextMateSharp 1.0.14
1
.csproj
TextMate/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit