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
|
---|---|---|---|---|---|---|---|---|
10064350 | <NME> IndentationReformatter.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Fixes/csharp indentation strategy (#5)
* fix from AvalonStudio csharp indentation strategy modified to actually
work as expected.
* install csharp indentation strategy for demo app.
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Fixes/csharp indentation strategy (#5) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064351 | <NME> IndentationReformatter.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Fixes/csharp indentation strategy (#5)
* fix from AvalonStudio csharp indentation strategy modified to actually
work as expected.
* install csharp indentation strategy for demo app.
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Fixes/csharp indentation strategy (#5) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064352 | <NME> IndentationReformatter.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Fixes/csharp indentation strategy (#5)
* fix from AvalonStudio csharp indentation strategy modified to actually
work as expected.
* install csharp indentation strategy for demo app.
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Fixes/csharp indentation strategy (#5) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064353 | <NME> IndentationReformatter.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Fixes/csharp indentation strategy (#5)
* fix from AvalonStudio csharp indentation strategy modified to actually
work as expected.
* install csharp indentation strategy for demo app.
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Fixes/csharp indentation strategy (#5) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064354 | <NME> IndentationReformatter.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Fixes/csharp indentation strategy (#5)
* fix from AvalonStudio csharp indentation strategy modified to actually
work as expected.
* install csharp indentation strategy for demo app.
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Fixes/csharp indentation strategy (#5) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064355 | <NME> IndentationReformatter.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Fixes/csharp indentation strategy (#5)
* fix from AvalonStudio csharp indentation strategy modified to actually
work as expected.
* install csharp indentation strategy for demo app.
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Fixes/csharp indentation strategy (#5) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064356 | <NME> IndentationReformatter.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Fixes/csharp indentation strategy (#5)
* fix from AvalonStudio csharp indentation strategy modified to actually
work as expected.
* install csharp indentation strategy for demo app.
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Fixes/csharp indentation strategy (#5) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064357 | <NME> IndentationReformatter.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace AvaloniaEdit.Indentation.CSharp
{
internal sealed class IndentationSettings
{
public string IndentString { get; set; } = "\t";
public bool LeaveEmptyLines { get; set; } = true;
}
internal sealed class IndentationReformatter
{
/// <summary>
/// An indentation block. Tracks the state of the indentation.
/// </summary>
private struct Block
{
/// <summary>
/// The indentation outside of the block.
/// </summary>
public string OuterIndent;
/// <summary>
/// The indentation inside the block.
/// </summary>
public string InnerIndent;
/// <summary>
/// The last word that was seen inside this block.
/// Because parenthesis open a sub-block and thus don't change their parent's LastWord,
/// this property can be used to identify the type of block statement (if, while, switch)
/// at the position of the '{'.
/// </summary>
public string LastWord;
/// <summary>
/// The type of bracket that opened this block (, [ or {
/// </summary>
public char Bracket;
/// <summary>
/// Gets whether there's currently a line continuation going on inside this block.
/// </summary>
public bool Continuation;
/// <summary>
/// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur
/// with if statements that don't use '{}'. They are not represented by a Block instance on
/// the stack, but are instead handled similar to line continuations.
/// This property is an integer because there might be multiple nested one-line-blocks.
/// As soon as there is a finished statement, OneLineBlock is reset to 0.
/// </summary>
public int OneLineBlock;
/// <summary>
/// The previous value of one-line-block before it was reset.
/// Used to restore the indentation of 'else' to the correct level.
/// </summary>
public int PreviousOneLineBlock;
public void ResetOneLineBlock()
{
PreviousOneLineBlock = OneLineBlock;
OneLineBlock = 0;
}
/// <summary>
/// Gets the line number where this block started.
/// </summary>
public int StartLine;
public void Indent(IndentationSettings set)
{
Indent(set.IndentString);
}
public void Indent(string indentationString)
{
OuterIndent = InnerIndent;
InnerIndent += indentationString;
Continuation = false;
ResetOneLineBlock();
LastWord = "";
}
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]",
StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock);
}
}
private StringBuilder _wordBuilder;
private Stack<Block> _blocks; // blocks contains all blocks outside of the current
private Block _block; // block is the current block
private bool _inString;
private bool _inChar;
private bool _verbatim;
private bool _escape;
private bool _lineComment;
private bool _blockComment;
private char _lastRealChar; // last non-comment char
public void Reformat(IDocumentAccessor doc, IndentationSettings set)
{
Init();
while (doc.MoveNext())
{
Step(doc, set);
}
}
public void Init()
{
_wordBuilder = new StringBuilder();
_blocks = new Stack<Block>();
_block = new Block
{
InnerIndent = "",
OuterIndent = "",
Bracket = '{',
Continuation = false,
LastWord = "",
OneLineBlock = 0,
PreviousOneLineBlock = 0,
StartLine = 0
};
_inString = false;
_inChar = false;
_verbatim = false;
_escape = false;
_lineComment = false;
_blockComment = false;
_lastRealChar = ' '; // last non-comment char
}
public void Step(IDocumentAccessor doc, IndentationSettings set)
{
var line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
var indent = new StringBuilder();
if (line.Length == 0)
{
// Special treatment for empty lines:
if (_blockComment || (_inString && _verbatim))
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
if (_block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
var oldBlock = _block;
var startInComment = _blockComment;
var startInString = (_inString && _verbatim);
#region Parse char by char
_lineComment = false;
_inChar = false;
_escape = false;
if (!_verbatim) _inString = false;
_lastRealChar = '\n';
var c = ' ';
var nextchar = line[0];
for (var i = 0; i < line.Length; i++)
{
if (_lineComment) break; // cancel parsing current line
var lastchar = c;
c = nextchar;
nextchar = i + 1 < line.Length ? line[i + 1] : '\n';
if (_escape)
{
_escape = false;
continue;
}
#region Check for comment/string chars
switch (c)
{
case '/':
if (_blockComment && lastchar == '*')
_blockComment = false;
if (!_inString && !_inChar)
{
if (!_blockComment && nextchar == '/')
_lineComment = true;
if (!_lineComment && nextchar == '*')
_blockComment = true;
}
break;
case '#':
if (!(_inChar || _blockComment || _inString))
_lineComment = true;
break;
case '"':
if (!(_inChar || _lineComment || _blockComment))
{
_inString = !_inString;
if (!_inString && _verbatim)
{
if (nextchar == '"')
{
_escape = true; // skip escaped quote
_inString = true;
}
else
{
_verbatim = false;
}
}
else if (_inString && lastchar == '@')
{
_verbatim = true;
}
}
break;
case '\'':
if (!(_inString || _lineComment || _blockComment))
{
_inChar = !_inChar;
}
break;
case '\\':
if ((_inString && !_verbatim) || _inChar)
_escape = true; // skip next character
break;
}
#endregion
if (_lineComment || _blockComment || _inString || _inChar)
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
continue;
}
if (!char.IsWhiteSpace(c) && c != '[' && c != '/')
{
if (_block.Bracket == '{')
_block.Continuation = true;
}
if (char.IsLetterOrDigit(c))
{
_wordBuilder.Append(c);
}
else
{
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c)
{
case '{':
_block.ResetOneLineBlock();
_blocks.Push(_block);
_block.StartLine = doc.LineNumber;
if (_block.LastWord == "switch")
{
_block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
}
else
{
_block.Indent(set);
}
_block.Bracket = '{';
break;
case '}':
while (_block.Bracket != '{')
{
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
}
if (_blocks.Count == 0) break;
_block = _blocks.Pop();
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case '(':
case '[':
_blocks.Push(_block);
if (_block.StartLine == doc.LineNumber)
_block.InnerIndent = _block.OuterIndent;
else
_block.StartLine = doc.LineNumber;
_block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new string(' ', i + 1)));
_block.Bracket = c;
break;
case ')':
if (_blocks.Count == 0) break;
if (_block.Bracket == '(')
{
_block = _blocks.Pop();
if (IsSingleStatementKeyword(_block.LastWord))
_block.Continuation = false;
}
break;
case ']':
if (_blocks.Count == 0) break;
if (_block.Bracket == '[')
_block = _blocks.Pop();
break;
case ';':
case ',':
_block.Continuation = false;
_block.ResetOneLineBlock();
break;
case ':':
if (_block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
{
_block.Continuation = false;
_block.ResetOneLineBlock();
}
break;
}
if (!char.IsWhiteSpace(c))
{
// register this char as last char
_lastRealChar = c;
}
#endregion
}
#endregion
if (_wordBuilder.Length > 0)
_block.LastWord = _wordBuilder.ToString();
_wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}')
{
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
}
else
{
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')')
{
indent.Remove(indent.Length - 1, 1);
}
else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']')
{
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':')
{
oldBlock.Continuation = true;
}
else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length)
{
if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
}
else if (_lastRealChar == ')')
{
if (IsSingleStatementKeyword(_block.LastWord))
{
_block.OneLineBlock++;
}
}
else if (_lastRealChar == 'e' && _block.LastWord == "else")
{
_block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock);
_block.Continuation = false;
oldBlock.OneLineBlock = _block.OneLineBlock - 1;
}
if (doc.IsReadOnly)
{
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == _block.StartLine &&
_block.StartLine < doc.LineNumber && _lastRealChar != ':')
{
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
foreach (var t in line)
{
if (!char.IsWhiteSpace(t))
break;
indent.Append(t);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ')
{
indent.Length -= 1;
}
_block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{')
{
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
char.IsWhiteSpace(doc.Text[indent.Length]))
{
doc.Text = indent + line;
}
}
private static string Repeat(string text, int count)
{
if (count == 0)
return string.Empty;
if (count == 1)
return text;
var b = new StringBuilder(text.Length * count);
for (var i = 0; i < count; i++)
b.Append(text);
return b.ToString();
}
private static bool IsSingleStatementKeyword(string keyword)
{
switch (keyword)
{
case "if":
case "for":
case "while":
case "do":
case "foreach":
case "using":
case "lock":
return true;
default:
return false;
}
}
private static bool TrimEnd(IDocumentAccessor doc)
{
var line = doc.Text;
if (!char.IsWhiteSpace(line[line.Length - 1])) return false;
// one space after an empty comment is allowed
if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal))
return false;
doc.Text = line.TrimEnd();
return true;
}
}
}
<MSG> Fixes/csharp indentation strategy (#5)
* fix from AvalonStudio csharp indentation strategy modified to actually
work as expected.
* install csharp indentation strategy for demo app.
<DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp
return;
indent.Append(_block.InnerIndent);
indent.Append(Repeat(set.IndentString, _block.OneLineBlock));
- if (_block.Continuation)
- indent.Append(set.IndentString);
+
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
| 1 | Fixes/csharp indentation strategy (#5) | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064358 | <NME> defining-modules.md
<BEF>
# Defining Modules
```js
var Apple = FruitMachine.define({
module: 'apple',
template: aTemplateFunction,
tag: 'section', // optional
classes: [ 'class-1', 'class-2'] // optional
```
<MSG> Update defining-modules.md
<DFF> @@ -1,12 +1,37 @@
-
# Defining Modules
```js
var Apple = FruitMachine.define({
module: 'apple',
- template: aTemplateFunction,
- tag: 'section', // optional
- classes: [ 'class-1', 'class-2'] // optional
-
+ template: templateFunction,
+ tag: 'section',
+ classes: [ 'class-1', 'class-2'],
+
+ // Event callbacks (optional)
+ onIntitalize: function(options){},
+ onSetup: function(){},
+ onTeardown: function(){},
+ onDestroy: function(){}
+});
```
+
+Define does two things:
+
+- It registers a View module internally for [Lazy]() View instantiation
+- It returns a constructor that can be [Explicitly]() instantiated.
+
+Internally `define` extends the default `FruitMachine.View.prototype` with the parameters you define. Many of these parameters can be overwritten in the options passed to the constructor on a per instance basis. It is important you don't declare any parameters that conflict with `FruitMachine.View.prototype` core API (check the [source]() if you are unsure).
+
+### Options
+
+- `module {String}` Your name for this View module.
+- `template {Function}` A function that will return the module's html (we like [Hogan](http://twitter.github.com/hogan.js/)
+- `tag {String}` The html tag to use on the root element (defaults to 'div') *(optional)*
+- `classes {Array}` A list of classes to add to the root element. *(optional)*
+- `onInitialize {Function}` Define a function to run when the VIew is first instantiated (only ever runs once) *(optional)*
+- `onSetup {Function}` A function to be run every time `View#setup()` is called. Should be used to bind any DOM event listeners. You can safely assume the presence of `this.el` at this point. *(optional)*
+- `onTeardown {Function}` A function to be run when `View#teardown()` or `View#destroy()` is called. `onTeardown` will also run if you attempt to setup an already 'setup' view.
+- `onDestroy {Function}` Run when `View#destroy()` is called (will only ever run once) *(optional)*
+
+
| 30 | Update defining-modules.md | 5 | .md | md | mit | ftlabs/fruitmachine |
10064359 | <NME> README.md
<BEF> # LoadJS
<img src="https://www.muicss.com/static/images/loadjs.svg" width="250px">
LoadJS is a tiny async loader for modern browsers (899 bytes).
[](https://david-dm.org/muicss/loadjs)
[](https://david-dm.org/muicss/loadjs?type=dev)
[](https://cdnjs.com/libraries/loadjs)
## Introduction
LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your <html> (possibly in the <head> tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload.
LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped).
Here's an example of what you can do with LoadJS:
```html
<script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script>
<script>
// define a dependency bundle and execute code when it loads
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
</script>
```
You can also use more advanced syntax for more options:
```html
<script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script>
<script>
// define a dependency bundle with advanced options
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
before: function(path, scriptEl) { /* execute code before fetch */ },
async: true, // load files synchronously or asynchronously (default: true)
numRetries: 3 // see caveats about using numRetries with async:false (default: 0),
returnPromise: false // return Promise object (default: false)
});
loadjs.ready('foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(depsNotFound) { /* foobar bundle load failed */ },
});
</script>
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development)
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production)
It's also available from these public CDNs:
* UNPKG
* [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development)
* [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production)
* CDNJS
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development)
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production)
You can also use it as a CJS or AMD module:
```bash
$ npm install --save loadjs
```
```javascript
var loadjs = require('loadjs');
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
## Browser Support
* IE9+ (`async: false` support only works in IE10+)
* Opera 12+
* Safari 5+
* Chrome
* Firefox
* iOS 6+
* Android 4.4+
LoadJS also detects script load failures from AdBlock Plus and Ghostery in:
* Safari
* Chrome
Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags)
## Documentation
1. Load a single file
```javascript
loadjs('/path/to/foo.js', function() {
/* foo.js loaded */
});
```
1. Fetch files in parallel and load them asynchronously
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() {
/* foo.js and bar.js loaded */
});
```
1. Fetch JavaScript, CSS and image files
```javascript
loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() {
/* foo.css, bar.png and thunk.js loaded */
});
```
1. Force treat file as CSS stylesheet
```javascript
loadjs(['css!/path/to/cssfile.custom'], function() {
/* cssfile.custom loaded as stylesheet */
});
```
1. Force treat file as image
```javascript
loadjs(['img!/path/to/image.custom'], function() {
/* image.custom loaded */
});
```
1. Add a bundle id
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use .ready() to define bundles and callbacks separately
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use multiple bundles in .ready() dependency lists
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar');
loadjs.ready(['foo', 'bar'], function() {
/* foo.js & bar1.js & bar2.js loaded */
});
```
1. Chain .ready() together
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs
.ready('foo', function() {
/* foo.js loaded */
})
.ready('bar', function() {
/* bar.js loaded */
});
```
1. Use Promises to register callbacks
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true})
.then(function() { /* foo.js & bar.js loaded */ })
1. Use .done() for more control
```javascript
loadjs.ready('my-awesome-plugin', {
success: function() {
myAwesomePlugin();
}
});
loadjs.ready('jquery', {
success: function() {
// plugin requires jquery
window.myAwesomePlugin = function() {
if (!window.jQuery) throw "jQuery is missing!";
};
// plugin is done loading
loadjs.done('my-awesome-plugin');
}
});
```
## Directory structure
});
```
1. Add an error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ }
});
```
1. Retry files before calling the error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ },
numRetries: 3
});
// NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries
```
1. Execute a callback before script tags are embedded
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
/* called for each script node before being embedded */
if (path === '/path/to/foo.js') scriptEl.crossOrigin = true;
}
});
```
1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`)
```javascript
loadjs(['/path/to/foo.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
document.body.appendChild(scriptEl);
/* return `false` to bypass default DOM insertion mechanism */
return false;
}
});
```
1. Use bundle ids in error callback
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk');
// wait for multiple depdendencies
loadjs.ready(['foo', 'bar', 'thunk'], {
success: function() {
// foo.js & bar.js & thunkor.js & thunky.js loaded
},
error: function(depsNotFound) {
if (depsNotFound.indexOf('foo') > -1) {}; // foo failed
if (depsNotFound.indexOf('bar') > -1) {}; // bar failed
if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed
}
});
```
1. Use .done() for more control
```javascript
loadjs.ready(['dependency1', 'dependency2'], function() {
/* run code after dependencies have been met */
});
function fn1() {
loadjs.done('dependency1');
}
function fn2() {
loadjs.done('dependency2');
}
```
1. Reset dependency trackers
```javascript
loadjs.reset();
```
1. Implement a require-like dependency manager
```javascript
var bundles = {
'bundleA': ['/file1.js', '/file2.js'],
'bundleB': ['/file3.js', '/file4.js']
};
function require(bundleIds, callbackFn) {
bundleIds.forEach(function(bundleId) {
if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId);
});
loadjs.ready(bundleIds, callbackFn);
}
require(['bundleA'], function() { /* bundleA loaded */ });
require(['bundleB'], function() { /* bundleB loaded */ });
require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ });
```
## Directory structure
<pre>
loadjs/
├── dist
│ ├── loadjs.js
│ ├── loadjs.min.js
│ └── loadjs.umd.js
├── examples
├── gulpfile.js
├── LICENSE.txt
├── package.json
├── README.md
├── src
│ └── loadjs.js
├── test
└── umd-templates
</pre>
## Development Quickstart
1. Install dependencies
* [nodejs](http://nodejs.org/)
* [npm](https://www.npmjs.org/)
* http-server (via npm)
1. Clone repository
```bash
$ git clone [email protected]:muicss/loadjs.git
$ cd loadjs
```
1. Install node dependencies using npm
```bash
$ npm install
```
1. Build examples
```bash
$ npm run build-examples
```
To view the examples you can use any static file server. To use the `nodejs` http-server module:
```bash
$ npm install http-server
$ npm run http-server -- -p 3000
```
Then visit [http://localhost:3000/examples](http://localhost:3000/examples)
1. Build distribution files
```bash
$ npm run build-dist
```
The files will be located in the `dist` directory.
1. Run tests
To run the browser tests first build the `loadjs` library:
```bash
$ npm run build-tests
```
Then visit [http://localhost:3000/test](http://localhost:3000/test)
1. Build all files
```bash
$ npm run build-all
```
<MSG> Update README.md
<DFF> @@ -187,23 +187,19 @@ Note: LoadJS treats empty CSS files as load failures in IE (to get around lack o
1. Use .done() for more control
```javascript
- loadjs.ready('my-awesome-plugin', {
+ loadjs.ready(['dependency1', 'dependency2'], {
success: function() {
- myAwesomePlugin();
+ // run code after dependencies have been met
}
});
- loadjs.ready('jquery', {
- success: function() {
- // plugin requires jquery
- window.myAwesomePlugin = function() {
- if (!window.jQuery) throw "jQuery is missing!";
- };
-
- // plugin is done loading
- loadjs.done('my-awesome-plugin');
- }
- });
+ function fn1() {
+ loadjs.done('dependency1');
+ }
+
+ function fn2() {
+ loadjs.done('dependency2');
+ }
```
## Directory structure
| 9 | Update README.md | 13 | .md | md | mit | muicss/loadjs |
10064360 | <NME> README.md
<BEF> # LoadJS
<img src="https://www.muicss.com/static/images/loadjs.svg" width="250px">
LoadJS is a tiny async loader for modern browsers (899 bytes).
[](https://david-dm.org/muicss/loadjs)
[](https://david-dm.org/muicss/loadjs?type=dev)
[](https://cdnjs.com/libraries/loadjs)
## Introduction
LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your <html> (possibly in the <head> tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload.
LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped).
Here's an example of what you can do with LoadJS:
```html
<script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script>
<script>
// define a dependency bundle and execute code when it loads
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
</script>
```
You can also use more advanced syntax for more options:
```html
<script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script>
<script>
// define a dependency bundle with advanced options
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
before: function(path, scriptEl) { /* execute code before fetch */ },
async: true, // load files synchronously or asynchronously (default: true)
numRetries: 3 // see caveats about using numRetries with async:false (default: 0),
returnPromise: false // return Promise object (default: false)
});
loadjs.ready('foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(depsNotFound) { /* foobar bundle load failed */ },
});
</script>
```
The latest version of LoadJS can be found in the `dist/` directory in this repository:
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development)
* [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production)
It's also available from these public CDNs:
* UNPKG
* [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development)
* [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production)
* CDNJS
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development)
* [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production)
You can also use it as a CJS or AMD module:
```bash
$ npm install --save loadjs
```
```javascript
var loadjs = require('loadjs');
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
## Browser Support
* IE9+ (`async: false` support only works in IE10+)
* Opera 12+
* Safari 5+
* Chrome
* Firefox
* iOS 6+
* Android 4.4+
LoadJS also detects script load failures from AdBlock Plus and Ghostery in:
* Safari
* Chrome
Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags)
## Documentation
1. Load a single file
```javascript
loadjs('/path/to/foo.js', function() {
/* foo.js loaded */
});
```
1. Fetch files in parallel and load them asynchronously
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() {
/* foo.js and bar.js loaded */
});
```
1. Fetch JavaScript, CSS and image files
```javascript
loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() {
/* foo.css, bar.png and thunk.js loaded */
});
```
1. Force treat file as CSS stylesheet
```javascript
loadjs(['css!/path/to/cssfile.custom'], function() {
/* cssfile.custom loaded as stylesheet */
});
```
1. Force treat file as image
```javascript
loadjs(['img!/path/to/image.custom'], function() {
/* image.custom loaded */
});
```
1. Add a bundle id
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use .ready() to define bundles and callbacks separately
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar');
loadjs.ready('foobar', function() {
/* foo.js & bar.js loaded */
});
```
1. Use multiple bundles in .ready() dependency lists
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar');
loadjs.ready(['foo', 'bar'], function() {
/* foo.js & bar1.js & bar2.js loaded */
});
```
1. Chain .ready() together
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs
.ready('foo', function() {
/* foo.js loaded */
})
.ready('bar', function() {
/* bar.js loaded */
});
```
1. Use Promises to register callbacks
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true})
.then(function() { /* foo.js & bar.js loaded */ })
1. Use .done() for more control
```javascript
loadjs.ready('my-awesome-plugin', {
success: function() {
myAwesomePlugin();
}
});
loadjs.ready('jquery', {
success: function() {
// plugin requires jquery
window.myAwesomePlugin = function() {
if (!window.jQuery) throw "jQuery is missing!";
};
// plugin is done loading
loadjs.done('my-awesome-plugin');
}
});
```
## Directory structure
});
```
1. Add an error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ }
});
```
1. Retry files before calling the error callback
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', {
success: function() { /* foo.js & bar.js loaded */ },
error: function(pathsNotFound) { /* at least one path didn't load */ },
numRetries: 3
});
// NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries
```
1. Execute a callback before script tags are embedded
```javascript
loadjs(['/path/to/foo.js', '/path/to/bar.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
/* called for each script node before being embedded */
if (path === '/path/to/foo.js') scriptEl.crossOrigin = true;
}
});
```
1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`)
```javascript
loadjs(['/path/to/foo.js'], {
success: function() {},
error: function(pathsNotFound) {},
before: function(path, scriptEl) {
document.body.appendChild(scriptEl);
/* return `false` to bypass default DOM insertion mechanism */
return false;
}
});
```
1. Use bundle ids in error callback
```javascript
loadjs('/path/to/foo.js', 'foo');
loadjs('/path/to/bar.js', 'bar');
loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk');
// wait for multiple depdendencies
loadjs.ready(['foo', 'bar', 'thunk'], {
success: function() {
// foo.js & bar.js & thunkor.js & thunky.js loaded
},
error: function(depsNotFound) {
if (depsNotFound.indexOf('foo') > -1) {}; // foo failed
if (depsNotFound.indexOf('bar') > -1) {}; // bar failed
if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed
}
});
```
1. Use .done() for more control
```javascript
loadjs.ready(['dependency1', 'dependency2'], function() {
/* run code after dependencies have been met */
});
function fn1() {
loadjs.done('dependency1');
}
function fn2() {
loadjs.done('dependency2');
}
```
1. Reset dependency trackers
```javascript
loadjs.reset();
```
1. Implement a require-like dependency manager
```javascript
var bundles = {
'bundleA': ['/file1.js', '/file2.js'],
'bundleB': ['/file3.js', '/file4.js']
};
function require(bundleIds, callbackFn) {
bundleIds.forEach(function(bundleId) {
if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId);
});
loadjs.ready(bundleIds, callbackFn);
}
require(['bundleA'], function() { /* bundleA loaded */ });
require(['bundleB'], function() { /* bundleB loaded */ });
require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ });
```
## Directory structure
<pre>
loadjs/
├── dist
│ ├── loadjs.js
│ ├── loadjs.min.js
│ └── loadjs.umd.js
├── examples
├── gulpfile.js
├── LICENSE.txt
├── package.json
├── README.md
├── src
│ └── loadjs.js
├── test
└── umd-templates
</pre>
## Development Quickstart
1. Install dependencies
* [nodejs](http://nodejs.org/)
* [npm](https://www.npmjs.org/)
* http-server (via npm)
1. Clone repository
```bash
$ git clone [email protected]:muicss/loadjs.git
$ cd loadjs
```
1. Install node dependencies using npm
```bash
$ npm install
```
1. Build examples
```bash
$ npm run build-examples
```
To view the examples you can use any static file server. To use the `nodejs` http-server module:
```bash
$ npm install http-server
$ npm run http-server -- -p 3000
```
Then visit [http://localhost:3000/examples](http://localhost:3000/examples)
1. Build distribution files
```bash
$ npm run build-dist
```
The files will be located in the `dist` directory.
1. Run tests
To run the browser tests first build the `loadjs` library:
```bash
$ npm run build-tests
```
Then visit [http://localhost:3000/test](http://localhost:3000/test)
1. Build all files
```bash
$ npm run build-all
```
<MSG> Update README.md
<DFF> @@ -187,23 +187,19 @@ Note: LoadJS treats empty CSS files as load failures in IE (to get around lack o
1. Use .done() for more control
```javascript
- loadjs.ready('my-awesome-plugin', {
+ loadjs.ready(['dependency1', 'dependency2'], {
success: function() {
- myAwesomePlugin();
+ // run code after dependencies have been met
}
});
- loadjs.ready('jquery', {
- success: function() {
- // plugin requires jquery
- window.myAwesomePlugin = function() {
- if (!window.jQuery) throw "jQuery is missing!";
- };
-
- // plugin is done loading
- loadjs.done('my-awesome-plugin');
- }
- });
+ function fn1() {
+ loadjs.done('dependency1');
+ }
+
+ function fn2() {
+ loadjs.done('dependency2');
+ }
```
## Directory structure
| 9 | Update README.md | 13 | .md | md | mit | muicss/loadjs |
10064361 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064362 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064363 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064364 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064365 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064366 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064367 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064368 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064369 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064370 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064371 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064372 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064373 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064374 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064375 | <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> 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 | Align the selection rectangle top position with the caret top position | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064376 | <NME> api.md
<BEF> # API
### fruitmachine.define()
View constructor
### View#add();
Adds a child view(s) to another View.
\nOptions:
- `name {String}` the name of the module
- `at` The child index at which to insert
- `inject` Injects the child's view element into the parent's
### View#remove();
Removes a child view from
its current View contexts
- `destroy {Function}` logic to permanently destroy all references
### Module#undefined
shint browser:true, node:true
### Module#util
Module Dependencies
### Module#exports()
Exports
### Module#Module
Module constructor
\nOptions:
layout.remove(apple, { el: false });
apple.remove({ el: false });
### View#id();
Returns a decendent module
by id, or if called with no
### Module#add()
Adds a child view(s) to another Module.
\nOptions:
myView.id('my_other_views_id');
//=> View
### View#module();
Returns the first descendent
View with the passed module type.
its current Module contexts
and also from the DOM unless
otherwise stated.
\nOptions:
- `fromDOM` Whether the element should be removed from the DOM (default `true`)
myView.modules('apple');
//=> View
### View#modules();
Returns a list of descendent
Views that match the module
// Apple is removed from the
// view structure, but not the DOM
layout.remove(apple, { el: false });
apple.remove({ el: false });
### Module#id()
myView.modules('apple');
//=> [ View, View, View ]
### View#each();
Calls the passed function
for each of the view's
//=> 'my_view_id'
myModule.id('my_other_views_id');
//=> Module
// Do stuff with each child view...
});
### View#toHTML();
Templates the view, including
any descendent views returning
\n*Example:*
// Assuming 'myModule' has 3 descendent
// views with the module type 'apple'
myModule.modules('apple');
//=> Module
### Module#modules()
Returns a list of descendent
Modules that match the module
type given (Similar to
Element.querySelectorAll();).
\n*Example:*
{{{child}}}
{{/children}}
### View#render();
Renders the view and replaces
the `view.el` with a freshly
rendered node.
\nFires a `render` event on the view.
### View#setup();
Sets up a view and all descendent
views.
// Do stuff with each child view...
});
### Module#toHTML()
Templates the view, including
any descendent views returning
an html string. All data in the
- `shallow` Does not recurse when `true` (default `false`)
### View#teardown();
Tearsdown a view and all descendent
views that have been setup.
*Example:*
<div class="slot-1">{{{<slot>}}}</div>
<div class="slot-2">{{{<slot>}}}</div>
- `shallow` Does not recurse when `true` (default `false`)
### View#destroy();
Completely destroys a view. This means
a view is torn down, removed from it's
### Module#_innerHTML()
Get the view's innerHTML
### Module#render()
Renders the view and replaces
the `view.el` with a freshly
rendered node.
- `fromDOM` Whether the view should be removed from DOM (default `true`)
### View#empty();
Destroys all children.
### View#inject();
Empties the destination element
and appends the view into it.
### View#appendTo();
Appends the view element into
the destination element.
### View#toJSON();
Returns a JSON represention of
a FruitMachine View. This can
\nYour custom `teardown` method is
called and a `teardown` event is fired.
Options:
- `shallow` Does not recurse when `true` (default `false`)
### Module#destroy()
Completely destroys a view. This means
Fires an event on a view.
### Model();
Model constructor.
### Model#get();
Gets a value by key
\nIf no key is given, the
whole model is returned.
### Model#set();
Sets data on the model.
\nAccepts either a key and
value, or an object literal.
### Model#clear();
CLears the data store.
### Model#destroy();
Deletes the data store.
### Model#toJSON();
Returns a shallow
clone of the data store.
\nYour custom `destroy` method is
called and a `destroy` event is fired.
NOTE: `.remove()` is only run on the view
that `.destroy()` is directly called on.
Options:
- `fromDOM` Whether the view should be removed from DOM (default `true`)
### Module#empty()
Destroys all children.
\nIs this needed?
### Module#mount()
Associate the view with an element.
Provide events and lifecycle methods
to fire when the element is newly
associated.
### Module#inject()
Empties the destination element
and appends the view into it.
### Module#appendTo()
Appends the view element into
the destination element.
### Module#insertBefore()
Inserts the view element before the
given child of the destination element.
### Module#toJSON()
Returns a JSON represention of
a FruitMachine Module. This can
be generated serverside and
passed into new FruitMachine(json)
to inflate serverside rendered
views.
### Module#events
Module Dependencies
### Module#listenerMap
Local vars
### Module#on()
Registers a event listener.
### Module#off()
Unregisters a event listener.
### Module#fire()
Fires an event on a view.
<MSG> New build
<DFF> @@ -4,7 +4,7 @@
View constructor
-### View#add();
+### add();
Adds a child view(s) to another View.
\nOptions:
@@ -12,7 +12,7 @@ Adds a child view(s) to another View.
- `at` The child index at which to insert
- `inject` Injects the child's view element into the parent's
-### View#remove();
+### remove();
Removes a child view from
its current View contexts
@@ -35,7 +35,7 @@ otherwise stated.
layout.remove(apple, { el: false });
apple.remove({ el: false });
-### View#id();
+### id();
Returns a decendent module
by id, or if called with no
@@ -48,7 +48,7 @@ arguments, returns this view's id.
myView.id('my_other_views_id');
//=> View
-### View#module();
+### module();
Returns the first descendent
View with the passed module type.
@@ -62,7 +62,7 @@ View's own module type is returned.
myView.modules('apple');
//=> View
-### View#modules();
+### modules();
Returns a list of descendent
Views that match the module
@@ -76,7 +76,7 @@ Element.querySelectorAll();).
myView.modules('apple');
//=> [ View, View, View ]
-### View#each();
+### each();
Calls the passed function
for each of the view's
@@ -87,7 +87,7 @@ children.
// Do stuff with each child view...
});
-### View#toHTML();
+### toHTML();
Templates the view, including
any descendent views returning
@@ -110,14 +110,14 @@ and printed with `{{{child}}}}`.
{{{child}}}
{{/children}}
-### View#render();
+### render();
Renders the view and replaces
the `view.el` with a freshly
rendered node.
\nFires a `render` event on the view.
-### View#setup();
+### setup();
Sets up a view and all descendent
views.
@@ -132,7 +132,7 @@ Options:
- `shallow` Does not recurse when `true` (default `false`)
-### View#teardown();
+### teardown();
Tearsdown a view and all descendent
views that have been setup.
@@ -143,7 +143,7 @@ Options:
- `shallow` Does not recurse when `true` (default `false`)
-### View#destroy();
+### destroy();
Completely destroys a view. This means
a view is torn down, removed from it's
@@ -159,21 +159,21 @@ Options:
- `fromDOM` Whether the view should be removed from DOM (default `true`)
-### View#empty();
+### empty();
Destroys all children.
-### View#inject();
+### inject();
Empties the destination element
and appends the view into it.
-### View#appendTo();
+### appendTo();
Appends the view element into
the destination element.
-### View#toJSON();
+### toJSON();
Returns a JSON represention of
a FruitMachine View. This can
@@ -190,32 +190,3 @@ Registers a event listener.
Fires an event on a view.
-### Model();
-
-Model constructor.
-
-### Model#get();
-
-Gets a value by key
-\nIf no key is given, the
-whole model is returned.
-
-### Model#set();
-
-Sets data on the model.
-\nAccepts either a key and
-value, or an object literal.
-
-### Model#clear();
-
-CLears the data store.
-
-### Model#destroy();
-
-Deletes the data store.
-
-### Model#toJSON();
-
-Returns a shallow
-clone of the data store.
-
| 15 | New build | 44 | .md | md | mit | ftlabs/fruitmachine |
10064377 | <NME> script.js
<BEF>
var Model = FruitMachine.Model;
// var collection = {
// get: function() {
// if (collection.cache) return collection.cache;
// var items = JSON.parse(localStorage.items || '[]');
// items = items.map(function(item) { return new Model(item); });
// return collection.cache = items;
// },
// toJSON: function() {
// return collection.get().map(function(model) { return model.toJSON(); });
// },
// save: function(items) {
// collection.cache = items;
// localStorage.items = JSON.stringify(collection.toJSON());
// },
// add: function(item){
// var items = collection.get();
// items.unshift(new Model(item));
// collection.save(items);
// },
// remove: function(index) {
// var items = collection.get();
// items.splice(index, 1);
// collection.save(items);
// }
// };
/**
* Usage
*/
// Create the FruitMachine View
var layout = new LayoutB();
var masthead = new Masthead({ id: 'child_1', model: { title: 'Todo' }});
var strawberry = new Strawberry({ id: 'child_2' });
var list = new List({ id: 'child_3' });
var collection = [];
layout
.add(masthead)
.add(strawberry)
.add(list)
.on('submit', onSubmit)
.on('closebuttonclick', onCloseButtonClick);
// Render the view,
// inject it into the
// DOM and call setup.
layout
.render()
.inject(document.getElementById('app'))
.setup();
function onSubmit(value) {
var model = new Model({ text: value });
var item = new ListItem({ model: model });
list
.add(item)
.render()
.setup();
collection.unshift(model);
}
function onCloseButtonClick(item) {
var index = collection.indexOf(item.model);
collection.splice(index, 1);
this.event.target.remove();
}
<MSG> Updated exmaples to use slot logic
<DFF> @@ -1,30 +1,5 @@
var Model = FruitMachine.Model;
-// var collection = {
-// get: function() {
-// if (collection.cache) return collection.cache;
-// var items = JSON.parse(localStorage.items || '[]');
-// items = items.map(function(item) { return new Model(item); });
-// return collection.cache = items;
-// },
-// toJSON: function() {
-// return collection.get().map(function(model) { return model.toJSON(); });
-// },
-// save: function(items) {
-// collection.cache = items;
-// localStorage.items = JSON.stringify(collection.toJSON());
-// },
-// add: function(item){
-// var items = collection.get();
-// items.unshift(new Model(item));
-// collection.save(items);
-// },
-// remove: function(index) {
-// var items = collection.get();
-// items.splice(index, 1);
-// collection.save(items);
-// }
-// };
/**
* Usage
@@ -32,19 +7,18 @@ var Model = FruitMachine.Model;
// Create the FruitMachine View
var layout = new LayoutB();
-var masthead = new Masthead({ id: 'child_1', model: { title: 'Todo' }});
-var strawberry = new Strawberry({ id: 'child_2' });
-var list = new List({ id: 'child_3' });
+var masthead = new Masthead({ model: { title: 'Todo' }});
+var strawberry = new Strawberry();
+var list = new List();
var collection = [];
layout
- .add(masthead)
- .add(strawberry)
- .add(list)
+ .add(masthead, 1)
+ .add(strawberry, 2)
+ .add(list, 3)
.on('submit', onSubmit)
.on('closebuttonclick', onCloseButtonClick);
-
// Render the view,
// inject it into the
// DOM and call setup.
@@ -56,12 +30,10 @@ layout
function onSubmit(value) {
var model = new Model({ text: value });
- var item = new ListItem({ model: model });
+ var item = new ListItem({ model: model }).render();
- list
- .add(item)
- .render()
- .setup();
+ list.add(item, { at: 0, inject: true });
+ item.setup();
collection.unshift(model);
}
| 9 | Updated exmaples to use slot logic | 37 | .js | js | mit | ftlabs/fruitmachine |
10064378 | <NME> database.js
<BEF>
/**
* Dummy Data Stores
*/
var database = {};
// Mock synchronous API
database.getSync = function() {
return [
{
id: 'article1',
title: 'Article 1'
},
{
id: 'article2',
title: 'Article 2'
},
{
id: 'article3',
title: 'Article 3'
},
{
id: 'article4',
title: 'Article 4'
},
{
id: 'article5',
title: 'Article 5'
}
];
};
// Mock asynchonous API
database.getAsync = function(id, callback) {
var database = {
article1: {
date: '3rd May 2012',
title: 'Article 1',
body: "<p>Big girl's blouse soft southern pansy cack-handed. Tha knows bloomin' 'eck. Is that thine t'foot o' our stairs. Cack-handed big girl's blouse dahn t'coil oil gerritetten. Appens as maybe shurrup where there's muck there's brass big girl's blouse breadcake. Shu' thi gob how much t'foot o' our stairs th'art nesh thee. A pint 'o mild nah then aye gi' o'er ah'll learn thi th'art nesh thee. Appens as maybe. Gi' o'er ey up. Ee by gum ey up shurrup eeh aye. Tha daft apeth where there's muck there's brass big girl's blouse nobbut a lad aye. Shu' thi gob ah'll box thi ears cack-handed. Nay lad. Bloomin' 'eck tintintin.</p>",
author: 'John Smith'
},
article2: {
date: '13th August 2012',
title: 'Article 2',
body: "<p>What's that when it's at ooam nah then t'foot o' our stairs tintintin. Eeh soft lad soft lad aye. Shu' thi gob what's that when it's at ooam chuffin' nora where's tha bin ee by gum be reet. What's that when it's at ooam soft lad wacken thi sen up mardy bum ne'ermind. Nay lad bloomin' 'eck ee by gum nay lad. Where there's muck there's brass mardy bum what's that when it's at ooam tell thi summat for nowt. Sup wi' 'im is that thine tell thi summat for nowt. Ey up wacken thi sen up nay lad ah'll box thi ears. Wacken thi sen up nobbut a lad shurrup what's that when it's at ooam. Where's tha bin tha what dahn t'coil oil dahn t'coil oil. Ne'ermind th'art nesh thee cack-handed chuffin' nora nah then mardy bum. Ne'ermind nah then.</p>",
author: 'John Smith'
},
article3: {
date: '27th July 2012',
title: 'Article 3',
body: "<p>Tha daft apeth nobbut a lad big girl's blouse gi' o'er chuffin' nora. Tell thi summat for nowt. Th'art nesh thee will 'e 'eckerslike will 'e 'eckerslike shurrup where there's muck there's brass. Ah'll gi' thi summat to rooer abaht michael palin. Soft lad by 'eck ah'll gi' thee a thick ear. Where there's muck there's brass th'art nesh thee shu' thi gob nah then. Nah then breadcake michael palin. Aye shu' thi gob how much nah then. Ah'll gi' thi summat to rooer abaht shurrup how much. Aye ne'ermind t'foot o' our stairs th'art nesh thee.</p>",
author: 'John Smith'
},
article4: {
date: '6th March 2013',
title: 'Article 4',
body: "<p>Th'art nesh thee dahn t'coil oil what's that when it's at ooam. Tell thi summat for nowt. Soft southern pansy michael palin any rooad. Ah'll gi' thee a thick ear ah'll gi' thi summat to rooer abaht ah'll learn thi bloomin' 'eck ne'ermind michael palin. Bobbar bloomin' 'eck tintintin sup wi' 'im gi' o'er bloomin' 'eck. Ah'll box thi ears bloomin' 'eck tha knows be reet breadcake appens as maybe. T'foot o' our stairs gi' o'er aye shurrup tell thi summat for nowt that's champion. Ee by gum face like a slapped arse where there's muck there's brass michael palin what's that when it's at ooam. God's own county ah'll box thi ears. Cack-handed appens as maybe shu' thi gob god's own county be reet.</p>",
author: 'John Smith'
},
article5: {
date: '24th December 2012',
title: 'Article 5',
body: '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.</p>',
author: 'John Smith'
}
};
setTimeout(function() {
callback(database[id]);
}, 100);
};
<MSG> Update database.js
<DFF> @@ -37,25 +37,25 @@ database.getAsync = function(id, callback) {
article1: {
date: '3rd May 2012',
title: 'Article 1',
- body: "<p>Big girl's blouse soft southern pansy cack-handed. Tha knows bloomin' 'eck. Is that thine t'foot o' our stairs. Cack-handed big girl's blouse dahn t'coil oil gerritetten. Appens as maybe shurrup where there's muck there's brass big girl's blouse breadcake. Shu' thi gob how much t'foot o' our stairs th'art nesh thee. A pint 'o mild nah then aye gi' o'er ah'll learn thi th'art nesh thee. Appens as maybe. Gi' o'er ey up. Ee by gum ey up shurrup eeh aye. Tha daft apeth where there's muck there's brass big girl's blouse nobbut a lad aye. Shu' thi gob ah'll box thi ears cack-handed. Nay lad. Bloomin' 'eck tintintin.</p>",
+ body: "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam volutpat sem dictum, bibendum orci sed, auctor nulla. Nullam mauris eros, lobortis quis mi quis, commodo pellentesque dolor. Fusce purus odio, rutrum id malesuada in, volutpat ut augue. Vivamus in neque posuere, porta ipsum sed, lacinia sem. In tortor turpis, rhoncus consequat elit nec, condimentum accumsan ipsum. Vestibulum sed pellentesque urna. Duis rutrum pulvinar accumsan. Integer sagittis ante enim, ac porttitor ligula rutrum quis.</p>",
author: 'John Smith'
},
article2: {
date: '13th August 2012',
title: 'Article 2',
- body: "<p>What's that when it's at ooam nah then t'foot o' our stairs tintintin. Eeh soft lad soft lad aye. Shu' thi gob what's that when it's at ooam chuffin' nora where's tha bin ee by gum be reet. What's that when it's at ooam soft lad wacken thi sen up mardy bum ne'ermind. Nay lad bloomin' 'eck ee by gum nay lad. Where there's muck there's brass mardy bum what's that when it's at ooam tell thi summat for nowt. Sup wi' 'im is that thine tell thi summat for nowt. Ey up wacken thi sen up nay lad ah'll box thi ears. Wacken thi sen up nobbut a lad shurrup what's that when it's at ooam. Where's tha bin tha what dahn t'coil oil dahn t'coil oil. Ne'ermind th'art nesh thee cack-handed chuffin' nora nah then mardy bum. Ne'ermind nah then.</p>",
+ body: "<p>Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer vulputate aliquet quam at aliquam. Praesent pellentesque mauris ut augue congue, sit amet mattis sapien ultrices. Phasellus at semper massa. Pellentesque sollicitudin egestas enim ac rhoncus. Vestibulum quis vehicula turpis, hendrerit dapibus nunc. Etiam eget libero efficitur, vehicula risus id, efficitur neque. Maecenas accumsan tincidunt ultrices. Vestibulum sagittis, felis sed commodo pharetra, velit dolor congue velit, nec porta leo leo sit amet neque. Donec imperdiet porttitor neque, eget faucibus odio eleifend ut.</p>",
author: 'John Smith'
},
article3: {
date: '27th July 2012',
title: 'Article 3',
- body: "<p>Tha daft apeth nobbut a lad big girl's blouse gi' o'er chuffin' nora. Tell thi summat for nowt. Th'art nesh thee will 'e 'eckerslike will 'e 'eckerslike shurrup where there's muck there's brass. Ah'll gi' thi summat to rooer abaht michael palin. Soft lad by 'eck ah'll gi' thee a thick ear. Where there's muck there's brass th'art nesh thee shu' thi gob nah then. Nah then breadcake michael palin. Aye shu' thi gob how much nah then. Ah'll gi' thi summat to rooer abaht shurrup how much. Aye ne'ermind t'foot o' our stairs th'art nesh thee.</p>",
+ body: "<p>Curabitur eget feugiat leo. Nulla lorem nisl, malesuada vel erat eu, mattis viverra magna. Praesent facilisis ornare tristique. Sed congue accumsan lacus, non consequat augue hendrerit et. Maecenas imperdiet placerat leo, sed auctor neque suscipit eget. Aliquam a porttitor massa. Quisque porttitor sed urna eget auctor.</p>",
author: 'John Smith'
},
article4: {
date: '6th March 2013',
title: 'Article 4',
- body: "<p>Th'art nesh thee dahn t'coil oil what's that when it's at ooam. Tell thi summat for nowt. Soft southern pansy michael palin any rooad. Ah'll gi' thee a thick ear ah'll gi' thi summat to rooer abaht ah'll learn thi bloomin' 'eck ne'ermind michael palin. Bobbar bloomin' 'eck tintintin sup wi' 'im gi' o'er bloomin' 'eck. Ah'll box thi ears bloomin' 'eck tha knows be reet breadcake appens as maybe. T'foot o' our stairs gi' o'er aye shurrup tell thi summat for nowt that's champion. Ee by gum face like a slapped arse where there's muck there's brass michael palin what's that when it's at ooam. God's own county ah'll box thi ears. Cack-handed appens as maybe shu' thi gob god's own county be reet.</p>",
+ body: "<p>Vestibulum consectetur, nunc sit amet sodales pharetra, arcu diam molestie ante, ac viverra erat justo id velit. Maecenas consequat fringilla lectus, id pretium ipsum viverra quis. Sed tortor urna, tincidunt ac laoreet eu, finibus finibus sem. Pellentesque venenatis risus sem, eu lacinia neque fermentum eu. In at dui ut odio elementum venenatis at eu tortor. Curabitur vel dui felis. Maecenas sollicitudin, erat sit amet facilisis vehicula, dolor lectus mattis libero, in sagittis justo lorem et libero. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum tincidunt ante eget ex gravida, vitae bibendum urna fermentum. Donec commodo magna vel malesuada volutpat. Etiam in ipsum nec est eleifend euismod. Mauris a justo justo. Aenean pulvinar aliquam ligula, at bibendum velit imperdiet at. Etiam euismod tristique ex quis placerat. Morbi mi lorem, cursus in tempus vitae, mollis in risus.</p>",
author: 'John Smith'
},
article5: {
@@ -69,4 +69,4 @@ database.getAsync = function(id, callback) {
setTimeout(function() {
callback(database[id]);
}, 100);
-};
\ No newline at end of file
+};
| 5 | Update database.js | 5 | .js | js | mit | ftlabs/fruitmachine |
10064379 | <NME> timsort.js
<BEF> /**
* Default minimum size of a run.
*/
const DEFAULT_MIN_MERGE = 32;
/**
* Minimum ordered subsequece required to do galloping.
*/
const DEFAULT_MIN_GALLOPING = 7;
/**
* Default tmp storage length. Can increase depending on the size of the
* smallest run to merge.
*/
const DEFAULT_TMP_STORAGE_LENGTH = 256;
/**
* Default alphabetical comparison of items.
*
* @param {string|object|number} a - First element to compare.
* @param {string|object|number} b - Second element to compare.
* @return {number} - A positive number if a.toString() > b.toString(), a
* negative number if .toString() < b.toString(), 0 otherwise.
*/
function alphabeticalCompare(a, b) {
if (a === b) {
return 0;
} else {
let aStr = String(a);
let bStr = String(b);
if (aStr === bStr) {
return 0;
} else {
return aStr < bStr ? -1 : 1;
}
}
}
/**
* Compute minimum run length for TimSort
*
* @param {number} n - The size of the array to sort.
*/
function minRunLength(n) {
let r = 0;
while (n >= DEFAULT_MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}
/**
* Counts the length of a monotonically ascending or strictly monotonically
* descending sequence (run) starting at array[lo] in the range [lo, hi). If
* the run is descending it is made ascending.
*
* @param {array} array - The array to reverse.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
* @param {function} compare - Item comparison function.
* @return {number} - The length of the run.
*/
function makeAscendingRun(array, lo, hi, compare) {
let runHi = lo + 1;
if (runHi === hi) {
return 1;
}
// Descending
if (compare(array[runHi++], array[lo]) < 0) {
while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
runHi++;
}
reverseRun(array, lo, runHi);
// Ascending
} else {
while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
runHi++;
}
}
return runHi - lo;
}
/**
* Reverse an array in the range [lo, hi).
*
* @param {array} array - The array to reverse.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
*/
function reverseRun(array, lo, hi) {
hi--;
while (lo < hi) {
let t = array[lo];
array[lo++] = array[hi];
array[hi--] = t;
}
}
/**
* Perform the binary sort of the array in the range [lo, hi) where start is
* the first element possibly out of order.
*
* @param {array} array - The array to sort.
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
* @param {number} start - First element possibly out of order.
* @param {function} compare - Item comparison function.
*/
function binaryInsertionSort(array, lo, hi, start, compare) {
if (start === lo) {
start++;
}
for (; start < hi; start++) {
let pivot = array[start];
// Ranges of the array where pivot belongs
let left = lo;
let right = start;
/*
* pivot >= array[i] for i in [lo, left)
* pivot < array[i] for i in in [right, start)
*/
while (left < right) {
let mid = (left + right) >>> 1;
if (compare(pivot, array[mid]) < 0) {
right = mid;
} else {
left = mid + 1;
}
}
/*
* Move elements right to make room for the pivot. If there are elements
* equal to pivot, left points to the first slot after them: this is also
* a reason for which TimSort is stable
*/
let n = start - left;
// Switch is just an optimization for small arrays
switch (n) {
case 3:
array[left + 3] = array[left + 2];
/* falls through */
case 2:
array[left + 2] = array[left + 1];
/* falls through */
case 1:
array[left + 1] = array[left];
break;
default:
while (n > 0) {
array[left + n] = array[left + n - 1];
n--;
}
}
array[left] = pivot;
}
}
/**
* Find the position at which to insert a value in a sorted range. If the range
* contains elements equal to the value the leftmost element index is returned
* (for stability).
*
* @param {number} value - Value to insert.
* @param {array} array - The array in which to insert value.
* @param {number} start - First element in the range.
* @param {number} length - Length of the range.
* @param {number} hint - The index at which to begin the search.
* @param {function} compare - Item comparison function.
* @return {number} - The index where to insert value.
*/
function gallopLeft(value, array, start, length, hint, compare) {
let lastOffset = 0;
let maxOffset = 0;
let offset = 1;
if (compare(value, array[start + hint]) > 0) {
maxOffset = length - hint;
while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
lastOffset += hint;
offset += hint;
// value <= array[start + hint]
} else {
maxOffset = hint + 1;
while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
let tmp = lastOffset;
lastOffset = hint - offset;
offset = hint - tmp;
}
/*
* Now array[start+lastOffset] < value <= array[start+offset], so value
* belongs somewhere in the range (start + lastOffset, start + offset]. Do a
* binary search, with invariant array[start + lastOffset - 1] < value <=
* array[start + offset].
*/
lastOffset++;
while (lastOffset < offset) {
let m = lastOffset + ((offset - lastOffset) >>> 1);
if (compare(value, array[start + m]) > 0) {
lastOffset = m + 1;
} else {
offset = m;
}
}
return offset;
}
/**
* Find the position at which to insert a value in a sorted range. If the range
* contains elements equal to the value the rightmost element index is returned
* (for stability).
*
* @param {number} value - Value to insert.
* @param {array} array - The array in which to insert value.
* @param {number} start - First element in the range.
* @param {number} length - Length of the range.
* @param {number} hint - The index at which to begin the search.
* @param {function} compare - Item comparison function.
* @return {number} - The index where to insert value.
*/
function gallopRight(value, array, start, length, hint, compare) {
let lastOffset = 0;
let maxOffset = 0;
let offset = 1;
if (compare(value, array[start + hint]) < 0) {
maxOffset = hint + 1;
while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
let tmp = lastOffset;
lastOffset = hint - offset;
offset = hint - tmp;
// value >= array[start + hint]
} else {
maxOffset = length - hint;
while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
lastOffset = offset;
offset = (offset << 1) + 1;
if (offset <= 0) {
offset = maxOffset;
}
}
if (offset > maxOffset) {
offset = maxOffset;
}
// Make offsets relative to start
lastOffset += hint;
offset += hint;
}
/*
* Now array[start+lastOffset] < value <= array[start+offset], so value
* belongs somewhere in the range (start + lastOffset, start + offset]. Do a
* binary search, with invariant array[start + lastOffset - 1] < value <=
* array[start + offset].
*/
lastOffset++;
while (lastOffset < offset) {
let m = lastOffset + ((offset - lastOffset) >>> 1);
if (compare(value, array[start + m]) < 0) {
offset = m;
} else {
lastOffset = m + 1;
}
}
return offset;
}
class TimSort {
array = null;
compare = null;
minGallop = DEFAULT_MIN_GALLOPING;
length = 0;
tmpStorageLength = DEFAULT_TMP_STORAGE_LENGTH;
stackLength = 0;
runStart = null;
runLength = null;
stackSize = 0;
constructor(array, compare) {
this.array = array;
this.compare = compare;
this.length = array.length;
if (this.length < 2 * DEFAULT_TMP_STORAGE_LENGTH) {
this.tmpStorageLength = this.length >>> 1;
}
this.tmp = new Array(this.tmpStorageLength);
this.stackLength =
(this.length < 120 ? 5 :
this.length < 1542 ? 10 :
this.length < 119151 ? 19 : 40);
this.runStart = new Array(this.stackLength);
this.runLength = new Array(this.stackLength);
}
/**
* Push a new run on TimSort's stack.
*
* @param {number} runStart - Start index of the run in the original array.
* @param {number} runLength - Length of the run;
*/
pushRun(runStart, runLength) {
this.runStart[this.stackSize] = runStart;
this.runLength[this.stackSize] = runLength;
this.stackSize += 1;
}
/**
* Merge runs on TimSort's stack so that the following holds for all i:
* 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1]
* 2) runLength[i - 2] > runLength[i - 1]
*/
mergeRuns() {
while (this.stackSize > 1) {
let n = this.stackSize - 2;
if ((n >= 1 &&
this.runLength[n - 1] <= this.runLength[n] + this.runLength[n + 1]) ||
(n >= 2 &&
this.runLength[n - 2] <= this.runLength[n] + this.runLength[n - 1])) {
if (this.runLength[n - 1] < this.runLength[n + 1]) {
n--;
}
} else if (this.runLength[n] > this.runLength[n + 1]) {
break;
}
this.mergeAt(n);
}
}
/**
* Merge all runs on TimSort's stack until only one remains.
*/
forceMergeRuns() {
while (this.stackSize > 1) {
let n = this.stackSize - 2;
if (n > 0 && this.runLength[n - 1] < this.runLength[n + 1]) {
n--;
}
this.mergeAt(n);
}
}
/**
* Merge the runs on the stack at positions i and i+1. Must be always be called
* with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack).
*
* @param {number} i - Index of the run to merge in TimSort's stack.
*/
mergeAt(i) {
let compare = this.compare;
let array = this.array;
let start1 = this.runStart[i];
let length1 = this.runLength[i];
let start2 = this.runStart[i + 1];
let length2 = this.runLength[i + 1];
this.runLength[i] = length1 + length2;
if (i === this.stackSize - 3) {
this.runStart[i + 1] = this.runStart[i + 2];
this.runLength[i + 1] = this.runLength[i + 2];
}
this.stackSize--;
/*
* Find where the first element in the second run goes in run1. Previous
* elements in run1 are already in place
*/
let k = gallopRight(array[start2], array, start1, length1, 0, compare);
start1 += k;
length1 -= k;
if (length1 === 0) {
return;
}
/*
* Find where the last element in the first run goes in run2. Next elements
* in run2 are already in place
*/
length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
if (length2 === 0) {
return;
}
/*
* Merge remaining runs. A tmp array with length = min(length1, length2) is
* used
*/
if (length1 <= length2) {
this.mergeLow(start1, length1, start2, length2);
} else {
this.mergeHigh(start1, length1, start2, length2);
}
}
/**
* Merge two adjacent runs in a stable way. The runs must be such that the
* first element of run1 is bigger than the first element in run2 and the
* last element of run1 is greater than all the elements in run2.
* The method should be called when run1.length <= run2.length as it uses
* TimSort temporary array to store run1. Use mergeHigh if run1.length >
* run2.length.
*
* @param {number} start1 - First element in run1.
* @param {number} length1 - Length of run1.
* @param {number} start2 - First element in run2.
* @param {number} length2 - Length of run2.
*/
mergeLow(start1, length1, start2, length2) {
let compare = this.compare;
let array = this.array;
let tmp = this.tmp;
let i = 0;
for (i = 0; i < length1; i++) {
tmp[i] = array[start1 + i];
}
let cursor1 = 0;
let cursor2 = start2;
let dest = start1;
array[dest++] = array[cursor2++];
if (--length2 === 0) {
for (i = 0; i < length1; i++) {
array[dest + i] = tmp[cursor1 + i];
}
return;
}
if (length1 === 1) {
for (i = 0; i < length2; i++) {
array[dest + i] = array[cursor2 + i];
}
array[dest + length2] = tmp[cursor1];
return;
}
let minGallop = this.minGallop;
while (true) {
let count1 = 0;
let count2 = 0;
let exit = false;
do {
if (compare(array[cursor2], tmp[cursor1]) < 0) {
array[dest++] = array[cursor2++];
count2++;
count1 = 0;
if (--length2 === 0) {
exit = true;
break;
}
} else {
array[dest++] = tmp[cursor1++];
count1++;
count2 = 0;
if (--length1 === 1) {
exit = true;
break;
}
}
} while ((count1 | count2) < minGallop);
if (exit) {
break;
}
do {
count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
if (count1 !== 0) {
for (i = 0; i < count1; i++) {
array[dest + i] = tmp[cursor1 + i];
}
dest += count1;
cursor1 += count1;
length1 -= count1;
if (length1 <= 1) {
exit = true;
break;
}
}
array[dest++] = array[cursor2++];
if (--length2 === 0) {
exit = true;
break;
}
count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
if (count2 !== 0) {
for (i = 0; i < count2; i++) {
array[dest + i] = array[cursor2 + i];
}
dest += count2;
cursor2 += count2;
length2 -= count2;
if (length2 === 0) {
exit = true;
break;
}
}
array[dest++] = tmp[cursor1++];
if (--length1 === 1) {
exit = true;
break;
}
minGallop--;
} while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
if (exit) {
break;
}
if (minGallop < 0) {
minGallop = 0;
}
minGallop += 2;
}
this.minGallop = minGallop;
if (minGallop < 1) {
this.minGallop = 1;
}
if (length1 === 1) {
for (i = 0; i < length2; i++) {
array[dest + i] = array[cursor2 + i];
}
array[dest + length2] = tmp[cursor1];
} else if (length1 === 0) {
throw new Error('mergeLow preconditions were not respected');
} else {
for (i = 0; i < length1; i++) {
array[dest + i] = tmp[cursor1 + i];
}
}
}
/**
* Merge two adjacent runs in a stable way. The runs must be such that the
* first element of run1 is bigger than the first element in run2 and the
* last element of run1 is greater than all the elements in run2.
* The method should be called when run1.length > run2.length as it uses
* TimSort temporary array to store run2. Use mergeLow if run1.length <=
* run2.length.
*
* @param {number} start1 - First element in run1.
* @param {number} length1 - Length of run1.
* @param {number} start2 - First element in run2.
* @param {number} length2 - Length of run2.
*/
mergeHigh(start1, length1, start2, length2) {
let compare = this.compare;
let array = this.array;
let tmp = this.tmp;
let i = 0;
for (i = 0; i < length2; i++) {
tmp[i] = array[start2 + i];
}
let cursor1 = start1 + length1 - 1;
let cursor2 = length2 - 1;
let dest = start2 + length2 - 1;
let customCursor = 0;
let customDest = 0;
array[dest--] = array[cursor1--];
if (--length1 === 0) {
customCursor = dest - (length2 - 1);
for (i = 0; i < length2; i++) {
array[customCursor + i] = tmp[i];
}
return;
}
if (length2 === 1) {
dest -= length1;
cursor1 -= length1;
customDest = dest + 1;
customCursor = cursor1 + 1;
for (i = length1 - 1; i >= 0; i--) {
array[customDest + i] = array[customCursor + i];
}
array[dest] = tmp[cursor2];
return;
}
let minGallop = this.minGallop;
while (true) {
let count1 = 0;
let count2 = 0;
let exit = false;
do {
if (compare(tmp[cursor2], array[cursor1]) < 0) {
array[dest--] = array[cursor1--];
count1++;
count2 = 0;
if (--length1 === 0) {
exit = true;
break;
}
} else {
array[dest--] = tmp[cursor2--];
count2++;
count1 = 0;
if (--length2 === 1) {
exit = true;
break;
}
}
} while ((count1 | count2) < minGallop);
if (exit) {
break;
}
do {
count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
if (count1 !== 0) {
dest -= count1;
cursor1 -= count1;
length1 -= count1;
customDest = dest + 1;
customCursor = cursor1 + 1;
for (i = count1 - 1; i >= 0; i--) {
array[customDest + i] = array[customCursor + i];
}
if (length1 === 0) {
exit = true;
break;
}
}
array[dest--] = tmp[cursor2--];
if (--length2 === 1) {
exit = true;
break;
}
count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
if (count2 !== 0) {
dest -= count2;
cursor2 -= count2;
length2 -= count2;
customDest = dest + 1;
customCursor = cursor2 + 1;
for (i = 0; i < count2; i++) {
array[customDest + i] = tmp[customCursor + i];
}
if (length2 <= 1) {
exit = true;
break;
}
}
array[dest--] = array[cursor1--];
if (--length1 === 0) {
exit = true;
break;
}
minGallop--;
} while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
if (exit) {
break;
}
if (minGallop < 0) {
minGallop = 0;
}
minGallop += 2;
}
this.minGallop = minGallop;
if (minGallop < 1) {
this.minGallop = 1;
}
if (length2 === 1) {
dest -= length1;
cursor1 -= length1;
customDest = dest + 1;
customCursor = cursor1 + 1;
for (i = length1 - 1; i >= 0; i--) {
array[customDest + i] = array[customCursor + i];
}
array[dest] = tmp[cursor2];
} else if (length2 === 0) {
throw new Error('mergeHigh preconditions were not respected');
} else {
customCursor = dest - (length2 - 1);
for (i = 0; i < length2; i++) {
array[customCursor + i] = tmp[i];
}
}
}
}
/**
* Sort an array in the range [lo, hi) using TimSort.
*
* @param {array} array - The array to sort.
* @param {function=} compare - Item comparison function. Default is
* alphabetical
* @param {number} lo - First element in the range (inclusive).
* @param {number} hi - Last element in the range.
* comparator.
*/
export function sort(array, compare, lo, hi) {
if (!Array.isArray(array)) {
throw new TypeError('Can only sort arrays');
}
/*
* Handle the case where a comparison function is not provided. We do
* lexicographic sorting
*/
if (!compare) {
compare = alphabeticalCompare;
} else if (typeof compare !== 'function') {
hi = lo;
lo = compare;
compare = alphabeticalCompare;
}
if (!lo) {
lo = 0;
}
if (!hi) {
hi = array.length;
}
let remaining = hi - lo;
// The array is already sorted
if (remaining < 2) {
return;
}
let runLength = 0;
// On small arrays binary sort can be used directly
if (remaining < DEFAULT_MIN_MERGE) {
runLength = makeAscendingRun(array, lo, hi, compare);
binaryInsertionSort(array, lo, hi, lo + runLength, compare);
return;
}
let ts = new TimSort(array, compare);
let minRun = minRunLength(remaining);
do {
runLength = makeAscendingRun(array, lo, hi, compare);
if (runLength < minRun) {
let force = remaining;
if (force > minRun) {
force = minRun;
}
binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
runLength = force;
}
// Push new run and merge if necessary
ts.pushRun(lo, runLength);
ts.mergeRuns();
// Go find next run
remaining -= runLength;
lo += runLength;
} while (remaining !== 0);
// Force merging of remaining runs
ts.forceMergeRuns();
}
<MSG> Improve lexicographic comparison of small integers
This commit adds an improved implementation of lexicographic comparison
of 32-bit integers as natively implemented in V8:
https://github.com/v8/v8/blob/8e02f47/src/runtime/runtime-numbers.cc#L197-L270
Unlike the V8 implementation, the implementation of log10 estimation
relies solely on comparisons whereas V8 uses a bit twiddling hack. My
guess is that this is why the pure-JS implementation is in fact able to
outperform V8.
<DFF> @@ -14,6 +14,42 @@ const DEFAULT_MIN_GALLOPING = 7;
*/
const DEFAULT_TMP_STORAGE_LENGTH = 256;
+/**
+ * Pre-computed powers of 10 for efficient lexicographic comparison of
+ * small integers.
+ */
+const POWERS_OF_TEN = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9]
+
+/**
+ * Estimate the logarithm base 10 of a small integer.
+ *
+ * @param {number} x - The integer to estimate the logarithm of.
+ * @return {number} - The estimated logarithm of the integer.
+ */
+function log10(x) {
+ if (x < 1e5) {
+ if (x < 1e2) {
+ return x < 1e1 ? 0 : 1;
+ }
+
+ if (x < 1e4) {
+ return x < 1e3 ? 2 : 3;
+ }
+
+ return 4;
+ }
+
+ if (x < 1e7) {
+ return x < 1e6 ? 5 : 6;
+ }
+
+ if (x < 1e9) {
+ return x < 1e8 ? 7 : 8;
+ }
+
+ return 9;
+}
+
/**
* Default alphabetical comparison of items.
*
@@ -25,18 +61,56 @@ const DEFAULT_TMP_STORAGE_LENGTH = 256;
function alphabeticalCompare(a, b) {
if (a === b) {
return 0;
+ }
- } else {
- let aStr = String(a);
- let bStr = String(b);
+ if (~~a === a && ~~b === b) {
+ if (a === 0 || b === 0) {
+ return a < b ? -1 : 1;
+ }
- if (aStr === bStr) {
- return 0;
+ if (a < 0 || b < 0) {
+ if (b >= 0) {
+ return -1;
+ }
- } else {
- return aStr < bStr ? -1 : 1;
+ if (a >= 0) {
+ return 1;
+ }
+
+ a = -a;
+ b = -b;
+ }
+
+ const al = log10(a);
+ const bl = log10(b);
+
+ let t = 0;
+
+ if (al < bl) {
+ a *= POWERS_OF_TEN[bl - al - 1];
+ b /= 10;
+ t = -1;
+ } else if (al > bl) {
+ b *= POWERS_OF_TEN[al - bl - 1];
+ a /= 10;
+ t = 1;
+ }
+
+ if (a === b) {
+ return t;
}
+
+ return a < b ? -1 : 1;
}
+
+ let aStr = String(a);
+ let bStr = String(b);
+
+ if (aStr === bStr) {
+ return 0;
+ }
+
+ return aStr < bStr ? -1 : 1;
}
/**
| 81 | Improve lexicographic comparison of small integers | 7 | .js | js | mit | mziccard/node-timsort |
10064380 | <NME> view-assembly.md
<BEF> ADDFILE
<MSG> Create view-assembly.md
<DFF> @@ -0,0 +1,2 @@
+
+# View Assembly
| 2 | Create view-assembly.md | 0 | .md | md | mit | ftlabs/fruitmachine |
10064381 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064382 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064383 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064384 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064385 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064386 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064387 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064388 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064389 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064390 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064391 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064392 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064393 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064394 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064395 | <NME> TextEditor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Avalonia;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Highlighting;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Utils;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Data;
using AvaloniaEdit.Search;
namespace AvaloniaEdit
{
/// <summary>
/// The text editor control.
/// Contains a scrollable TextArea.
/// </summary>
public class TextEditor : TemplatedControl, ITextEditorComponent
{
#region Constructors
static TextEditor()
{
FocusableProperty.OverrideDefaultValue<TextEditor>(true);
HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged);
IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged);
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
public TextEditor() : this(new TextArea())
{
}
/// <summary>
/// Creates a new TextEditor instance.
/// </summary>
protected TextEditor(TextArea textArea) : this(textArea, new TextDocument())
{
}
protected TextEditor(TextArea textArea, TextDocument document)
{
this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea));
textArea.TextView.Services.AddService(this);
SetValue(OptionsProperty, textArea.Options);
SetValue(DocumentProperty, document);
textArea[!BackgroundProperty] = this[!BackgroundProperty];
}
#endregion
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
TextArea.Focus();
e.Handled = true;
}
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// This is a dependency property.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
/// <summary>
/// Raises the <see cref="DocumentChanged"/> event.
/// </summary>
protected virtual void OnDocumentChanged(EventArgs e)
{
DocumentChanged?.Invoke(this, e);
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged);
PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
TextArea.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged);
PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler);
}
OnDocumentChanged(EventArgs.Empty);
OnTextChanged(EventArgs.Empty);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the options currently used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler);
}
TextArea.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == WordWrapProperty)
{
if (WordWrap)
{
_horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility;
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck;
}
}
}
private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
HandleIsOriginalChanged(e);
}
}
private void OnTextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
#endregion
#region Text property
/// <summary>
/// Gets/Sets the text of the current document.
/// </summary>
public string Text
{
get
{
var document = Document;
return document != null ? document.Text : string.Empty;
}
set
{
var document = GetDocument();
document.Text = value ?? string.Empty;
// after replacing the full text, the caret is positioned at the end of the document
// - reset it to the beginning.
CaretOffset = 0;
document.UndoStack.ClearAll();
}
}
private TextDocument GetDocument()
{
var document = Document;
if (document == null)
throw ThrowUtil.NoDocumentAssigned();
return document;
}
/// <summary>
/// Occurs when the Text property changes.
/// </summary>
public event EventHandler TextChanged;
/// <summary>
/// Raises the <see cref="TextChanged"/> event.
/// </summary>
protected virtual void OnTextChanged(EventArgs e)
{
TextChanged?.Invoke(this, e);
}
#endregion
#region TextArea / ScrollViewer properties
private readonly TextArea textArea;
private SearchPanel searchPanel;
private bool wasSearchPanelOpened;
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer");
ScrollViewer.Content = TextArea;
searchPanel = SearchPanel.Install(this);
}
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnAttachedToLogicalTree(e);
if (searchPanel != null && wasSearchPanelOpened)
{
searchPanel.Open();
}
}
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
if (searchPanel != null)
{
wasSearchPanelOpened = searchPanel.IsOpened;
if (searchPanel.IsOpened)
searchPanel.Close();
}
}
/// <summary>
/// Gets the text area.
/// </summary>
public TextArea TextArea => textArea;
/// <summary>
/// Gets the search panel.
/// </summary>
public SearchPanel SearchPanel => searchPanel;
/// <summary>
/// Gets the scroll viewer used by the text editor.
/// This property can return null if the template has not been applied / does not contain a scroll viewer.
/// </summary>
internal ScrollViewer ScrollViewer { get; private set; }
#endregion
#region Syntax highlighting
/// <summary>
/// The <see cref="SyntaxHighlighting"/> property.
/// </summary>
public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty =
AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting");
/// <summary>
/// Gets/sets the syntax highlighting definition used to colorize the text.
/// </summary>
public IHighlightingDefinition SyntaxHighlighting
{
get => GetValue(SyntaxHighlightingProperty);
set => SetValue(SyntaxHighlightingProperty, value);
}
private IVisualLineTransformer _colorizer;
private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition);
}
private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
{
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Remove(_colorizer);
_colorizer = null;
}
if (newValue != null)
{
_colorizer = CreateColorizer(newValue);
if (_colorizer != null)
{
textArea.TextView.LineTransformers.Insert(0, _colorizer);
}
}
}
/// <summary>
/// Creates the highlighting colorizer for the specified highlighting definition.
/// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
/// </summary>
/// <returns></returns>
protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
{
if (highlightingDefinition == null)
throw new ArgumentNullException(nameof(highlightingDefinition));
return new HighlightingColorizer(highlightingDefinition);
}
#endregion
#region WordWrap
/// <summary>
/// Word wrap dependency property.
/// </summary>
public static readonly StyledProperty<bool> WordWrapProperty =
AvaloniaProperty.Register<TextEditor, bool>("WordWrap");
/// <summary>
/// Specifies whether the text editor uses word wrapping.
/// </summary>
/// <remarks>
/// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the
/// HorizontalScrollBarVisibility setting.
/// </remarks>
public bool WordWrap
{
get => GetValue(WordWrapProperty);
set => SetValue(WordWrapProperty, value);
}
#endregion
#region IsReadOnly
/// <summary>
/// IsReadOnly dependency property.
/// </summary>
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly");
/// <summary>
/// Specifies whether the user can change the text editor content.
/// Setting this property will replace the
/// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>.
/// </summary>
public bool IsReadOnly
{
get => GetValue(IsReadOnlyProperty);
set => SetValue(IsReadOnlyProperty, value);
}
private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is TextEditor editor)
{
if ((bool)e.NewValue)
editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance;
else
editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance;
}
}
#endregion
#region IsModified
/// <summary>
/// Dependency property for <see cref="IsModified"/>
/// </summary>
public static readonly StyledProperty<bool> IsModifiedProperty =
AvaloniaProperty.Register<TextEditor, bool>("IsModified");
/// <summary>
/// Gets/Sets the 'modified' flag.
/// </summary>
public bool IsModified
{
get => GetValue(IsModifiedProperty);
set => SetValue(IsModifiedProperty, value);
}
private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var document = editor?.Document;
if (document != null)
{
var undoStack = document.UndoStack;
if ((bool)e.NewValue)
{
if (undoStack.IsOriginalFile)
undoStack.DiscardOriginalFileMarker();
}
else
{
undoStack.MarkAsOriginalFile();
}
}
}
private void HandleIsOriginalChanged(PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsOriginalFile")
{
var document = Document;
if (document != null)
{
SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile);
}
}
}
#endregion
#region ShowLineNumbers
/// <summary>
/// ShowLineNumbers dependency property.
/// </summary>
public static readonly StyledProperty<bool> ShowLineNumbersProperty =
AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers");
/// <summary>
/// Specifies whether line numbers are shown on the left to the text view.
/// </summary>
public bool ShowLineNumbers
{
get => GetValue(ShowLineNumbersProperty);
set => SetValue(ShowLineNumbersProperty, value);
}
private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
if (editor == null) return;
var leftMargins = editor.TextArea.LeftMargins;
if ((bool)e.NewValue)
{
var lineNumbers = new LineNumberMargin();
var line = (Line)DottedLineMargin.Create();
leftMargins.Insert(0, lineNumbers);
leftMargins.Insert(1, line);
var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor };
line.Bind(Shape.StrokeProperty, lineNumbersForeground);
lineNumbers.Bind(ForegroundProperty, lineNumbersForeground);
}
else
{
for (var i = 0; i < leftMargins.Count; i++)
{
if (leftMargins[i] is LineNumberMargin)
{
leftMargins.RemoveAt(i);
if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i]))
{
leftMargins.RemoveAt(i);
}
break;
}
}
}
}
#endregion
#region LineNumbersForeground
/// <summary>
/// LineNumbersForeground dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty =
AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray);
/// <summary>
/// Gets/sets the Brush used for displaying the foreground color of line numbers.
/// </summary>
public IBrush LineNumbersForeground
{
get => GetValue(LineNumbersForegroundProperty);
set => SetValue(LineNumbersForegroundProperty, value);
}
private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e)
{
var editor = e.Sender as TextEditor;
var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin;
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
#endregion
#region TextBoxBase-like methods
/// <summary>
/// Appends text to the end of the document.
/// </summary>
public void AppendText(string textData)
{
var document = GetDocument();
document.Insert(document.TextLength, textData);
}
/// <summary>
/// Begins a group of document changes.
/// </summary>
public void BeginChange()
{
GetDocument().BeginUpdate();
}
/// <summary>
/// Copies the current selection to the clipboard.
/// </summary>
public void Copy()
{
if (CanCopy)
{
ApplicationCommands.Copy.Execute(null, TextArea);
}
}
/// <summary>
/// Removes the current selection and copies it to the clipboard.
/// </summary>
public void Cut()
{
if (CanCut)
{
ApplicationCommands.Cut.Execute(null, TextArea);
}
}
/// <summary>
/// Begins a group of document changes and returns an object that ends the group of document
/// changes when it is disposed.
/// </summary>
public IDisposable DeclareChangeBlock()
{
return GetDocument().RunUpdate();
}
/// <summary>
/// Removes the current selection without copying it to the clipboard.
/// </summary>
public void Delete()
{
if(CanDelete)
{
ApplicationCommands.Delete.Execute(null, TextArea);
}
}
/// <summary>
/// Ends the current group of document changes.
/// </summary>
public void EndChange()
{
GetDocument().EndUpdate();
}
/// <summary>
/// Scrolls one line down.
/// </summary>
public void LineDown()
{
//if (scrollViewer != null)
// scrollViewer.LineDown();
}
/// <summary>
/// Scrolls to the left.
/// </summary>
public void LineLeft()
{
//if (scrollViewer != null)
// scrollViewer.LineLeft();
}
/// <summary>
/// Scrolls to the right.
/// </summary>
public void LineRight()
{
//if (scrollViewer != null)
// scrollViewer.LineRight();
}
/// <summary>
/// Scrolls one line up.
/// </summary>
public void LineUp()
{
//if (scrollViewer != null)
// scrollViewer.LineUp();
}
/// <summary>
/// Scrolls one page down.
/// </summary>
public void PageDown()
{
//if (scrollViewer != null)
// scrollViewer.PageDown();
}
/// <summary>
/// Scrolls one page up.
/// </summary>
public void PageUp()
{
//if (scrollViewer != null)
// scrollViewer.PageUp();
}
/// <summary>
/// Scrolls one page left.
/// </summary>
public void PageLeft()
{
//if (scrollViewer != null)
// scrollViewer.PageLeft();
}
/// <summary>
/// Scrolls one page right.
/// </summary>
public void PageRight()
{
//if (scrollViewer != null)
// scrollViewer.PageRight();
}
/// <summary>
/// Pastes the clipboard content.
/// </summary>
public void Paste()
{
if (CanPaste)
{
ApplicationCommands.Paste.Execute(null, TextArea);
}
}
/// <summary>
/// Redoes the most recent undone command.
/// </summary>
/// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns>
public bool Redo()
{
if (CanRedo)
{
ApplicationCommands.Redo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Scrolls to the end of the document.
/// </summary>
public void ScrollToEnd()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToEnd();
}
/// <summary>
/// Scrolls to the start of the document.
/// </summary>
public void ScrollToHome()
{
ApplyTemplate(); // ensure scrollViewer is created
ScrollViewer?.ScrollToHome();
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToHorizontalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToHorizontalOffset(offset);
}
/// <summary>
/// Scrolls to the specified position in the document.
/// </summary>
public void ScrollToVerticalOffset(double offset)
{
ApplyTemplate(); // ensure scrollViewer is created
//if (scrollViewer != null)
// scrollViewer.ScrollToVerticalOffset(offset);
}
/// <summary>
/// Selects the entire text.
/// </summary>
public void SelectAll()
{
if (CanSelectAll)
{
ApplicationCommands.SelectAll.Execute(null, TextArea);
}
}
/// <summary>
/// Undoes the most recent command.
/// </summary>
/// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns>
public bool Undo()
{
if (CanUndo)
{
ApplicationCommands.Undo.Execute(null, TextArea);
return true;
}
return false;
}
/// <summary>
/// Gets if the most recent undone command can be redone.
/// </summary>
public bool CanRedo
{
get { return ApplicationCommands.Redo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if the most recent command can be undone.
/// </summary>
public bool CanUndo
{
get { return ApplicationCommands.Undo.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be copied
/// </summary>
public bool CanCopy
{
get { return ApplicationCommands.Copy.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be cut
/// </summary>
public bool CanCut
{
get { return ApplicationCommands.Cut.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text in editor can be pasted
/// </summary>
public bool CanPaste
{
get { return ApplicationCommands.Paste.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if selected text in editor can be deleted
/// </summary>
public bool CanDelete
{
get { return ApplicationCommands.Delete.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text the editor can select all
/// </summary>
public bool CanSelectAll
{
get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); }
}
/// <summary>
/// Gets if text editor can activate the search panel
/// </summary>
public bool CanSearch
{
get { return searchPanel != null; }
}
/// <summary>
/// Gets the vertical size of the document.
/// </summary>
public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the current document region.
/// </summary>
public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0;
/// <summary>
/// Gets the horizontal size of the viewport.
/// </summary>
public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0;
/// <summary>
/// Gets the vertical scroll position.
/// </summary>
public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0;
/// <summary>
/// Gets the horizontal scroll position.
/// </summary>
public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0;
#endregion
#region TextBox methods
/// <summary>
/// Gets/Sets the selected text.
/// </summary>
public string SelectedText
{
get
{
// We'll get the text from the whole surrounding segment.
// This is done to ensure that SelectedText.Length == SelectionLength.
if (textArea.Document != null && !textArea.Selection.IsEmpty)
return textArea.Document.GetText(textArea.Selection.SurroundingSegment);
return string.Empty;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var textArea = TextArea;
if (textArea.Document != null)
{
var offset = SelectionStart;
var length = SelectionLength;
textArea.Document.Replace(offset, length, value);
// keep inserted text selected
textArea.Selection = Selection.Create(textArea, offset, offset + value.Length);
}
}
}
/// <summary>
/// Gets/sets the caret position.
/// </summary>
public int CaretOffset
{
get
{
return textArea.Caret.Offset;
}
set
{
textArea.Caret.Offset = value;
}
}
/// <summary>
/// Gets/sets the start position of the selection.
/// </summary>
public int SelectionStart
{
get
{
if (textArea.Selection.IsEmpty)
return textArea.Caret.Offset;
else
return textArea.Selection.SurroundingSegment.Offset;
}
set => Select(value, SelectionLength);
}
/// <summary>
/// Gets/sets the length of the selection.
/// </summary>
public int SelectionLength
{
get
{
if (!textArea.Selection.IsEmpty)
return textArea.Selection.SurroundingSegment.Length;
else
return 0;
}
set => Select(SelectionStart, value);
}
/// <summary>
/// Selects the specified text section.
/// </summary>
public void Select(int start, int length)
{
var documentLength = Document?.TextLength ?? 0;
if (start < 0 || start > documentLength)
throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength);
if (length < 0 || start + length > documentLength)
throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start));
TextArea.Selection = Selection.Create(TextArea, start, start + length);
TextArea.Caret.Offset = start + length;
}
/// <summary>
/// Gets the number of lines in the document.
/// </summary>
public int LineCount
{
get
{
var document = Document;
if (document != null)
return document.LineCount;
return 1;
}
}
/// <summary>
/// Clears the text.
/// </summary>
public void Clear()
{
Text = string.Empty;
}
#endregion
#region Loading from stream
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Load(Stream stream)
{
using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8))
{
Text = reader.ReadToEnd();
SetValue(EncodingProperty, (object)reader.CurrentEncoding);
}
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Loads the text from the stream, auto-detecting the encoding.
/// </summary>
public void Load(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO:load
//using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
//{
// Load(fs);
//}
}
/// <summary>
/// Encoding dependency property.
/// </summary>
public static readonly StyledProperty<Encoding> EncodingProperty =
AvaloniaProperty.Register<TextEditor, Encoding>("Encoding");
/// <summary>
/// Gets/sets the encoding used when the file is saved.
/// </summary>
/// <remarks>
/// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly.
/// The <see cref="Save(Stream)"/> method uses the encoding specified in this property.
/// </remarks>
public Encoding Encoding
{
get => GetValue(EncodingProperty);
set => SetValue(EncodingProperty, value);
}
/// <summary>
/// Saves the text to the stream.
/// </summary>
/// <remarks>
/// This method sets <see cref="IsModified"/> to false.
/// </remarks>
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
var encoding = Encoding;
var document = Document;
var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
document?.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetValue(IsModifiedProperty, (object)false);
}
/// <summary>
/// Saves the text to the file.
/// </summary>
public void Save(string fileName)
{
if (fileName == null)
throw new ArgumentNullException(nameof(fileName));
// TODO: save
//using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
//{
// Save(fs);
//}
}
#endregion
#region PointerHover events
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
TextView.PreviewPointerHoverEvent;
/// <summary>
/// the pointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
TextView.PointerHoverEvent;
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
TextView.PreviewPointerHoverStoppedEvent;
/// <summary>
/// the pointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
TextView.PointerHoverStoppedEvent;
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
#endregion
#region ScrollBarVisibility
/// <summary>
/// Dependency property for <see cref="HorizontalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the horizontal scroll bar visibility.
/// </summary>
public ScrollBarVisibility HorizontalScrollBarVisibility
{
get => GetValue(HorizontalScrollBarVisibilityProperty);
set => SetValue(HorizontalScrollBarVisibilityProperty, value);
}
private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto;
/// <summary>
/// Dependency property for <see cref="VerticalScrollBarVisibility"/>
/// </summary>
public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>();
/// <summary>
/// Gets/Sets the vertical scroll bar visibility.
/// </summary>
public ScrollBarVisibility VerticalScrollBarVisibility
{
get => GetValue(VerticalScrollBarVisibilityProperty);
set => SetValue(VerticalScrollBarVisibilityProperty, value);
}
#endregion
object IServiceProvider.GetService(Type serviceType)
{
return TextArea.GetService(serviceType);
}
/// <summary>
/// Gets the text view position from a point inside the editor.
/// </summary>
/// <param name="point">The position, relative to top left
/// corner of TextEditor control</param>
/// <returns>The text view position, or null if the point is outside the document.</returns>
public TextViewPosition? GetPositionFromPoint(Point point)
{
if (Document == null)
return null;
var textView = TextArea.TextView;
Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView);
return textView.GetPosition(tpoint);
}
/// <summary>
/// Scrolls to the specified line.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollToLine(int line)
{
ScrollTo(line, -1);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (layout engine must have run prior).
/// </summary>
public void ScrollTo(int line, int column)
{
const double MinimumScrollFraction = 0.3;
ScrollTo(line, column, VisualYPosition.LineMiddle,
null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction);
}
/// <summary>
/// Scrolls to the specified line/column.
/// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior).
/// </summary>
/// <param name="line">Line to scroll to.</param>
/// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param>
/// <param name="yPositionMode">The mode how to reference the Y position of the line.</param>
/// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param>
/// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param>
public void ScrollTo(int line, int column, VisualYPosition yPositionMode,
double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDocument document = textView.Document;
if (ScrollViewer != null && document != null)
{
if (line < 1)
line = 1;
if (line > document.LineCount)
line = document.LineCount;
ILogicalScrollable scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll)
{
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0)
{
DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(
new TextViewPosition(line, Math.Max(1, column)),
yPositionMode);
double targetX = ScrollViewer.Offset.X;
double targetY = ScrollViewer.Offset.Y;
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) >
minimumScrollFraction * ScrollViewer.Viewport.Height)
{
targetY = Math.Max(0, verticalPos);
}
if (column > 0)
{
if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2)
{
double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2);
if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) >
minimumScrollFraction * ScrollViewer.Viewport.Width)
{
targetX = 0;
}
}
else
{
targetX = 0;
}
}
if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y)
ScrollViewer.Offset = new Vector(targetX, targetY);
}
}
}
}
<MSG> Merge pull request #254 from AvaloniaUI/allow-scroll-below-document
Fix allow scroll below document
<DFF> @@ -59,6 +59,8 @@ namespace AvaloniaEdit
IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged);
ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged);
LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged);
+ FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged);
+ FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged);
}
/// <summary>
@@ -562,6 +564,21 @@ namespace AvaloniaEdit
lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue);
}
+
+ private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue);
+ }
+
+ private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e)
+ {
+ var editor = e.Sender as TextEditor;
+
+ editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue);
+ }
+
#endregion
#region TextBoxBase-like methods
| 17 | Merge pull request #254 from AvaloniaUI/allow-scroll-below-document | 0 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10064396 | <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 = new Grid($element, gridOptions).render()
.option("data", data);
var $row = $element.find("." + grid.oddRowClass);
grid.editItem($row);
$editRow = grid._content.find("." + grid.editRowClass);
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(deletedArgs.row.length, 1, "row element is provided in updating event args");
});
module("paging");
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> Deleting: Method 'deleteItem' accepts row or rowElement to delete
<DFF> @@ -824,7 +824,7 @@ $(function() {
grid = new Grid($element, gridOptions).render()
.option("data", data);
- var $row = $element.find("." + grid.oddRowClass);
+ var $row = $element.find("." + grid.oddRowClass).eq(0);
grid.editItem($row);
$editRow = grid._content.find("." + grid.editRowClass);
@@ -1005,6 +1005,37 @@ $(function() {
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).render()
+ .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");
| 32 | Deleting: Method 'deleteItem' accepts row or rowElement to delete | 1 | .js | tests | mit | tabalinas/jsgrid |
10064397 | <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 = new Grid($element, gridOptions).render()
.option("data", data);
var $row = $element.find("." + grid.oddRowClass);
grid.editItem($row);
$editRow = grid._content.find("." + grid.editRowClass);
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(deletedArgs.row.length, 1, "row element is provided in updating event args");
});
module("paging");
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> Deleting: Method 'deleteItem' accepts row or rowElement to delete
<DFF> @@ -824,7 +824,7 @@ $(function() {
grid = new Grid($element, gridOptions).render()
.option("data", data);
- var $row = $element.find("." + grid.oddRowClass);
+ var $row = $element.find("." + grid.oddRowClass).eq(0);
grid.editItem($row);
$editRow = grid._content.find("." + grid.editRowClass);
@@ -1005,6 +1005,37 @@ $(function() {
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).render()
+ .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");
| 32 | Deleting: Method 'deleteItem' accepts row or rowElement to delete | 1 | .js | tests | mit | tabalinas/jsgrid |
10064398 | <NME> README.md
<BEF> # Lumen Passport
[](https://travis-ci.org/dusterio/lumen-passport)
[](https://codeclimate.com/github/dusterio/lumen-passport/badges)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](https://packagist.org/packages/dusterio/lumen-passport)
[](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:
This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
```php
Dusterio\LumenPassport\LumenPassport::routes($this->app->router);
```
You can add that into an existing group, or add use this route registrar independently like so;
```php
Dusterio\LumenPassport\LumenPassport::routes($this->app->router, ['prefix' => 'v1/oauth']);
```
## User model
}
```
### 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> r Readme
<DFF> @@ -125,13 +125,13 @@ Next, you should call the LumenPassport::routes method within the boot method of
This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:
```php
-Dusterio\LumenPassport\LumenPassport::routes($this->app->router);
+Dusterio\LumenPassport\LumenPassport::routes($this->app);
```
You can add that into an existing group, or add use this route registrar independently like so;
```php
-Dusterio\LumenPassport\LumenPassport::routes($this->app->router, ['prefix' => 'v1/oauth']);
+Dusterio\LumenPassport\LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);
```
## User model
| 2 | r Readme | 2 | .md | md | mit | dusterio/lumen-passport |
10064399 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064400 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064401 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064402 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064403 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064404 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064405 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064406 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064407 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064408 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064409 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064410 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064411 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064412 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064413 | <NME> TextMate.cs
<BEF> using System;
using System.Linq;
using TextMateSharp.Grammars;
using TextMateSharp.Model;
using TextMateSharp.Registry;
using TextMateSharp.Themes;
namespace AvaloniaEdit.TextMate
{
public static class TextMate
{
public static void RegisterExceptionHandler(Action<Exception> handler)
{
_exceptionHandler = handler;
}
public static Installation InstallTextMate(
this TextEditor editor,
IRegistryOptions registryOptions,
bool initCurrentDocument = true)
{
return new Installation(editor, registryOptions, initCurrentDocument);
}
transformer.SetTheme(theme);
editor.InvalidateVisual();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
private TMModel _tmModel;
private TextMateColoringTransformer _transformer;
public IRegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } }
public TextEditorModel EditorModel { get { return _editorModel; } }
public Installation(TextEditor editor, IRegistryOptions registryOptions, bool initCurrentDocument = true)
{
_textMateRegistryOptions = registryOptions;
_textMateRegistry = new Registry(registryOptions);
_editor = editor;
SetTheme(registryOptions.GetDefaultTheme());
editor.DocumentChanged += OnEditorOnDocumentChanged;
if (initCurrentDocument)
{
OnEditorOnDocumentChanged(editor, EventArgs.Empty);
}
}
public void SetGrammar(string scopeName)
{
_grammar = _textMateRegistry.LoadGrammar(scopeName);
GetOrCreateTransformer().SetGrammar(_grammar);
_editor.TextArea.TextView.Redraw();
}
public void SetTheme(IRawTheme theme)
{
_textMateRegistry.SetTheme(theme);
GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme());
_tmModel?.InvalidateLine(0);
_editorModel?.InvalidateViewPortLines();
}
public void Dispose()
{
_editor.DocumentChanged -= OnEditorOnDocumentChanged;
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
DisposeTransformer(_transformer);
}
void OnEditorOnDocumentChanged(object sender, EventArgs args)
{
try
{
DisposeEditorModel(_editorModel);
DisposeTMModel(_tmModel, _transformer);
_editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler);
_tmModel = new TMModel(_editorModel);
_tmModel.SetGrammar(_grammar);
_transformer = GetOrCreateTransformer();
_transformer.SetModel(_editor.Document, _tmModel);
_tmModel.AddModelTokensChangedListener(_transformer);
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
TextMateColoringTransformer GetOrCreateTransformer()
{
var transformer = _editor.TextArea.TextView.LineTransformers.OfType<TextMateColoringTransformer>().FirstOrDefault();
if (transformer is null)
{
transformer = new TextMateColoringTransformer(
_editor.TextArea.TextView, _exceptionHandler);
_editor.TextArea.TextView.LineTransformers.Add(transformer);
}
return transformer;
}
static void DisposeTransformer(TextMateColoringTransformer transformer)
{
if (transformer == null)
return;
transformer.Dispose();
}
static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer)
{
if (tmModel == null)
return;
if (transformer != null)
tmModel.RemoveModelTokensChangedListener(transformer);
tmModel.Dispose();
}
static void DisposeEditorModel(TextEditorModel editorModel)
{
if (editorModel == null)
return;
editorModel.Dispose();
}
}
static Action<Exception> _exceptionHandler;
}
}
<MSG> Redraw the text area when setting the theme so viewport lines are repainted
<DFF> @@ -26,7 +26,7 @@ namespace AvaloniaEdit.TextMate
transformer.SetTheme(theme);
- editor.InvalidateVisual();
+ editor.TextArea.TextView.Redraw();
}
private static TextMateColoringTransformer GetOrCreateTransformer(this TextEditor editor)
| 1 | Redraw the text area when setting the theme so viewport lines are repainted | 1 | .cs | TextMate/TextMate | mit | AvaloniaUI/AvaloniaEdit |
10064414 | <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 right"); }); 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 transfered"); }); test("destroy", function() { grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), ""); strictEqual($element.data(JSGRID_DATA_KEY), undefined); }); test("jquery adapter repeated call changes options", 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"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invoke method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { 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; } }; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value"); }); test("option changing event handlers", function() { 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); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test"); equal(optionChangingEventArgs.oldValue, "testValue"); equal(optionChangingEventArgs.newValue, "newTestValue"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue"); equal(optionChangedEventArgs.option, "another"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}).render(), headerGrid, headerGridTable, bodyGrid, bodyGridTable; ok($element.hasClass(grid.containerClass)); equal($element.children().length, 3); ok($element.children().eq(0).hasClass(grid.gridHeaderClass)); ok($element.children().eq(1).hasClass(grid.gridBodyClass)); ok($element.children().eq(2).hasClass(grid.pagerContainerClass)); headerGrid = $element.children().eq(0); headerGridTable = headerGrid.children().first(); ok(headerGridTable.hasClass(grid.tableClass)); ok(headerGrid.find("." + grid.headerRowClass).length); ok(headerGrid.find("." + grid.filterRowClass).length); ok(headerGrid.find("." + grid.insertRowClass).length); ok(grid._headerRow.hasClass(grid.headerRowClass)); ok(grid._filterRow.hasClass(grid.filterRowClass)); ok(grid._insertRow.hasClass(grid.insertRowClass)); bodyGrid = $element.children().eq(1); bodyGridTable = bodyGrid.children().first(); ok(bodyGridTable.hasClass(grid.tableClass)); equal(grid._content.parent()[0], bodyGridTable[0]); ok(bodyGridTable.find("." + grid.noDataRowClass).length); equal(bodyGridTable.text(), grid.noDataText); }); module("loadingg"); test("loading with controller", function() { var $element = $("#jsGrid"), 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); grid.loadData(); equal(grid.data, data); }); test("autoload", function() { 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; grid = new Grid($element, gridOptions).render(); equal(grid.data, data); }); test("loading filtered data", function() { 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() { grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.data.length, 2, "data loaded with filter"); deepEqual(loadedArgs.data, filteredData); }); 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 = new Grid($element, gridOptions).render(); grid.search(); equal(grid.data.length, 2, "data filtered"); strictEqual(grid.pageIndex, 1, "pageIndex reseted"); strictEqual(grid._sortField, null, "sortField reseted"); strictEqual(grid._sortOrder, "asc", "sortOrder reseted"); }); controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } { name: "test", filterTemplate: function() { var result = this.filterControl = $("<input />").attr("type", "text").addClass("filter-input"); return result; } } $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", { name: "field", filterTemplate: function() { var result = this.filterControl = $("<input />").attr("type", "text"); return result; }, filterValue: function(value) { }, 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, var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input />").attr("type", "text"); return result; }, filterValue: function(value) { 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() { grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }); }); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); grid = new Grid($element, gridOptions).render() .option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1); equal(grid._content.text(), grid.noDataText); }); test("nodatarow customize content", function() { grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, grid = new Grid($element, gridOptions).render() .option("data", []); equal(grid._content.text(), noDataMessage); }); ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { }, grid = new Grid($element, gridOptions).render(); equal(grid._content.children().length, 3); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); }); test("custom rowClass callback", function() { } }, grid = new Grid($element, gridOptions); grid.loadData(); }); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1); equal(grid._content.find(".test2").length, 1); equal(grid._content.find(".test3").length, 1); }); test("rowClick standard handler", function() { 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; } } }, $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("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 []; .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseover." + JSGRID, $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseover doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { equal(grid.option("data").length, 1, "new load strategy is applied"); }); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid); equal(refreshedEventArgs.grid, grid); equal(grid._content.find("." + grid.oddRowClass).length, 2); }); test("grid fields normalization", function() { 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() { field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1"); equal(field1.title, "title1"); field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2"); equal(field2.title, "title2"); }); test("grid fields header and item rendering", function() { ] }, 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, { name: "test", insertTemplate: function() { var result = this.insertControl = $("<input />").attr("type", "text").addClass("insert-input"); return result; } } }) ] }, 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"); var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input />").attr("type", "text"); return result; }, insertValue: function() { { 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.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }); }); test("insert data", function() { 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"); }); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test"); equal(grid.data.length, 1, "data inserted"); ok(inserted, "controller insertItem called"); deepEqual(grid.data[0], { field: "test" }, "right data inserted"); equal(insertedArgs.item.field, "test"); }); 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" } { name: "test", editTemplate: function(value) { var result = this.editControl = $("<input />").attr("type", "text").val(value).addClass("edit-input"); return result; } } 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; } }, { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input />").attr("type", "text").val(value); return result; }, editValue: function() { }); 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) { grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.item, { field: "new value" }); equal(updatingArgs.itemIndex, 0); equal(updatingArgs.row.length, 1); ok(updated, "controller updateItem called"); deepEqual(grid.data[0], { field: "new value" }, "right 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.item, { field: "new value" }); equal(updatedArgs.itemIndex, 0); equal(updatedArgs.row.length, 1); }); test("cancel edit", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input />").attr("type", "text").val(value); return result; }, editValue: function() { }); 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"); }); grid.cancelEdit(); ok(!updated, "controller updateItem was not called"); deepEqual(grid.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"); }); 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" }), { grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }); equal(deletingArgs.itemIndex, 0); equal(deletingArgs.row.length, 1); ok(deleted, "controller deleteItem called"); equal(grid.data.length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }); equal(deletedArgs.itemIndex, 0); equal(deletedArgs.row.length, 1); }); 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]; pageSize: 2 }).render(); ok(!grid._pagerContainer.is(":visible")); ok(!grid._pagerContainer.html()); grid.paging = true; grid.refresh(); ok(grid._pagerContainer.is(":visible")); ok(grid._pagerContainer.html()); grid.option("data", [{}, {}]); ok(!grid._pagerContainer.is(":visible")); ok(!grid._pagerContainer.html()); }); test("external pagerContainer", function() { var $pagerContainer = $("<div />").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) pageSize: 2 }).render(); ok($pagerContainer.is(":visible")); ok($pagerContainer.html()); }); test("pager rendered and works correctly", function() { var $element = $("#jsGrid"), pager, grid = new Grid($element, { new jsGrid.Field({ name: "text", title: "title", pageButtonCount: 3 }).render(); equal(grid._pagesCount(), 5, "right page count"); equal(grid.pageIndex, 1, "pageIndex initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); 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(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigative by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigative by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening not visible next page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening not visible prev page moves first displaying page backward"); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20, gridOptions, grid, pager, i; for(i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } gridOptions = { pageLoading: true, paging: true, pageSize: 7, 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 }, } }; grid = new Grid($element, gridOptions).render(); grid.loadData(); pager = grid._pagerContainer; equal(grid.data.length, 7, "loaded one page of data"); equal(grid.data[0].value, 1, "loaded right data start value"); equal(grid.data[grid.data.length - 1].value, 7, "loaded right 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); equal(grid.data.length, 6, "loaded last page of data"); equal(grid.data[0].value, 15, "loaded right data start value"); equal(grid.data[grid.data.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"); }); inserting: true, fields: [ { test("sorting", function() { var $element = $("#jsGrid"), th, gridOptions = { sorting: true, } } ] }, 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"); }, grid = new Grid($element, gridOptions).render(); th = grid._headerRow.find("th").eq(0); th.trigger("click"); equal(grid._sortOrder, "asc"); equal(grid._sortField, grid.fields[0]); equal(grid.data[0].value, 1); equal(grid.data[1].value, 2); equal(grid.data[2].value, 3); ok(th.hasClass(grid.sortableClass)); ok(th.hasClass(grid.sortAscClass)); th.trigger("click"); equal(grid._sortOrder, "desc"); equal(grid._sortField, grid.fields[0]); equal(grid.data[0].value, 3); equal(grid.data[1].value, 2); equal(grid.data[2].value, 1); ok(!th.hasClass(grid.sortAscClass)); ok(th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, th, gridOptions = { sorting: true, 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"); grid = new Grid($element, gridOptions).render(); th = grid._headerRow.find("th").eq(0); th.trigger("click"); equal(grid._sortOrder, "asc"); equal(grid._sortField, grid.fields[0]); equal(loadFilter.sortOrder, "asc"); equal(loadFilter.sortField, "value"); th.trigger("click"); equal(grid._sortOrder, "desc"); equal(grid._sortField, grid.fields[0]); equal(loadFilter.sortOrder, "desc"); equal(loadFilter.sortField, "value"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"), th, gridOptions = { sorting: true, data: [ { value: 3 }, 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"); fields: [ { name: "value", sorting: false } ] }, grid = new Grid($element, gridOptions).render(); th = grid._headerRow.find("th").eq(0); th.trigger("click"); equal(grid._sortField, null); equal(grid.data[0].value, 3); equal(grid.data[1].value, 2); equal(grid.data[2].value, 1); ok(!th.hasClass(grid.sortAscClass)); }); }); }, 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> Tests: Code refactoring <DFF> @@ -24,20 +24,20 @@ $(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 right"); + deepEqual(grid.complexOption, gridOptions.complexOption, "object option copied correctly"); }); test("jquery adapter creation", function() { var gridOptions = { - option: "test" - }, + 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 transfered"); + 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() { @@ -49,11 +49,11 @@ $(function() { grid.destroy(); - strictEqual($element.html(), ""); - strictEqual($element.data(JSGRID_DATA_KEY), undefined); + strictEqual($element.html(), "", "content is removed"); + strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); - test("jquery adapter repeated call changes options", function() { + test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" @@ -70,7 +70,7 @@ $(function() { equal(grid.option, "new test", "option changed"); }); - test("jquery adapter invoke method", function() { + test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { @@ -95,11 +95,11 @@ $(function() { $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); - equal(testOption, "value"); + equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); - equal(testOption, "new_value"); + equal(testOption, "new_value", "set option value"); }); test("option changing event handlers", | 181 | Tests: Code refactoring | 181 | .js | tests | mit | tabalinas/jsgrid |
10064415 | <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 right"); }); 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 transfered"); }); test("destroy", function() { grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), ""); strictEqual($element.data(JSGRID_DATA_KEY), undefined); }); test("jquery adapter repeated call changes options", 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"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invoke method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { 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; } }; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value"); }); test("option changing event handlers", function() { 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); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test"); equal(optionChangingEventArgs.oldValue, "testValue"); equal(optionChangingEventArgs.newValue, "newTestValue"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue"); equal(optionChangedEventArgs.option, "another"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}).render(), headerGrid, headerGridTable, bodyGrid, bodyGridTable; ok($element.hasClass(grid.containerClass)); equal($element.children().length, 3); ok($element.children().eq(0).hasClass(grid.gridHeaderClass)); ok($element.children().eq(1).hasClass(grid.gridBodyClass)); ok($element.children().eq(2).hasClass(grid.pagerContainerClass)); headerGrid = $element.children().eq(0); headerGridTable = headerGrid.children().first(); ok(headerGridTable.hasClass(grid.tableClass)); ok(headerGrid.find("." + grid.headerRowClass).length); ok(headerGrid.find("." + grid.filterRowClass).length); ok(headerGrid.find("." + grid.insertRowClass).length); ok(grid._headerRow.hasClass(grid.headerRowClass)); ok(grid._filterRow.hasClass(grid.filterRowClass)); ok(grid._insertRow.hasClass(grid.insertRowClass)); bodyGrid = $element.children().eq(1); bodyGridTable = bodyGrid.children().first(); ok(bodyGridTable.hasClass(grid.tableClass)); equal(grid._content.parent()[0], bodyGridTable[0]); ok(bodyGridTable.find("." + grid.noDataRowClass).length); equal(bodyGridTable.text(), grid.noDataText); }); module("loadingg"); test("loading with controller", function() { var $element = $("#jsGrid"), 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); grid.loadData(); equal(grid.data, data); }); test("autoload", function() { 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; grid = new Grid($element, gridOptions).render(); equal(grid.data, data); }); test("loading filtered data", function() { 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() { grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.data.length, 2, "data loaded with filter"); deepEqual(loadedArgs.data, filteredData); }); 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 = new Grid($element, gridOptions).render(); grid.search(); equal(grid.data.length, 2, "data filtered"); strictEqual(grid.pageIndex, 1, "pageIndex reseted"); strictEqual(grid._sortField, null, "sortField reseted"); strictEqual(grid._sortOrder, "asc", "sortOrder reseted"); }); controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } { name: "test", filterTemplate: function() { var result = this.filterControl = $("<input />").attr("type", "text").addClass("filter-input"); return result; } } $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", { name: "field", filterTemplate: function() { var result = this.filterControl = $("<input />").attr("type", "text"); return result; }, filterValue: function(value) { }, 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, var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input />").attr("type", "text"); return result; }, filterValue: function(value) { 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() { grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }); }); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); grid = new Grid($element, gridOptions).render() .option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1); equal(grid._content.text(), grid.noDataText); }); test("nodatarow customize content", function() { grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, grid = new Grid($element, gridOptions).render() .option("data", []); equal(grid._content.text(), noDataMessage); }); ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { }, grid = new Grid($element, gridOptions).render(); equal(grid._content.children().length, 3); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); }); test("custom rowClass callback", function() { } }, grid = new Grid($element, gridOptions); grid.loadData(); }); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1); equal(grid._content.find(".test2").length, 1); equal(grid._content.find(".test3").length, 1); }); test("rowClick standard handler", function() { 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; } } }, $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("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 []; .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseover." + JSGRID, $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseover doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { equal(grid.option("data").length, 1, "new load strategy is applied"); }); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid); equal(refreshedEventArgs.grid, grid); equal(grid._content.find("." + grid.oddRowClass).length, 2); }); test("grid fields normalization", function() { 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() { field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1"); equal(field1.title, "title1"); field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2"); equal(field2.title, "title2"); }); test("grid fields header and item rendering", function() { ] }, 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, { name: "test", insertTemplate: function() { var result = this.insertControl = $("<input />").attr("type", "text").addClass("insert-input"); return result; } } }) ] }, 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"); var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input />").attr("type", "text"); return result; }, insertValue: function() { { 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.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }); }); test("insert data", function() { 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"); }); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test"); equal(grid.data.length, 1, "data inserted"); ok(inserted, "controller insertItem called"); deepEqual(grid.data[0], { field: "test" }, "right data inserted"); equal(insertedArgs.item.field, "test"); }); 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" } { name: "test", editTemplate: function(value) { var result = this.editControl = $("<input />").attr("type", "text").val(value).addClass("edit-input"); return result; } } 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; } }, { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input />").attr("type", "text").val(value); return result; }, editValue: function() { }); 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) { grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.item, { field: "new value" }); equal(updatingArgs.itemIndex, 0); equal(updatingArgs.row.length, 1); ok(updated, "controller updateItem called"); deepEqual(grid.data[0], { field: "new value" }, "right 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.item, { field: "new value" }); equal(updatedArgs.itemIndex, 0); equal(updatedArgs.row.length, 1); }); test("cancel edit", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input />").attr("type", "text").val(value); return result; }, editValue: function() { }); 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"); }); grid.cancelEdit(); ok(!updated, "controller updateItem was not called"); deepEqual(grid.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"); }); 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" }), { grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }); equal(deletingArgs.itemIndex, 0); equal(deletingArgs.row.length, 1); ok(deleted, "controller deleteItem called"); equal(grid.data.length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }); equal(deletedArgs.itemIndex, 0); equal(deletedArgs.row.length, 1); }); 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]; pageSize: 2 }).render(); ok(!grid._pagerContainer.is(":visible")); ok(!grid._pagerContainer.html()); grid.paging = true; grid.refresh(); ok(grid._pagerContainer.is(":visible")); ok(grid._pagerContainer.html()); grid.option("data", [{}, {}]); ok(!grid._pagerContainer.is(":visible")); ok(!grid._pagerContainer.html()); }); test("external pagerContainer", function() { var $pagerContainer = $("<div />").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) pageSize: 2 }).render(); ok($pagerContainer.is(":visible")); ok($pagerContainer.html()); }); test("pager rendered and works correctly", function() { var $element = $("#jsGrid"), pager, grid = new Grid($element, { new jsGrid.Field({ name: "text", title: "title", pageButtonCount: 3 }).render(); equal(grid._pagesCount(), 5, "right page count"); equal(grid.pageIndex, 1, "pageIndex initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); 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(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigative by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigative by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening not visible next page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening not visible prev page moves first displaying page backward"); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20, gridOptions, grid, pager, i; for(i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } gridOptions = { pageLoading: true, paging: true, pageSize: 7, 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 }, } }; grid = new Grid($element, gridOptions).render(); grid.loadData(); pager = grid._pagerContainer; equal(grid.data.length, 7, "loaded one page of data"); equal(grid.data[0].value, 1, "loaded right data start value"); equal(grid.data[grid.data.length - 1].value, 7, "loaded right 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); equal(grid.data.length, 6, "loaded last page of data"); equal(grid.data[0].value, 15, "loaded right data start value"); equal(grid.data[grid.data.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"); }); inserting: true, fields: [ { test("sorting", function() { var $element = $("#jsGrid"), th, gridOptions = { sorting: true, } } ] }, 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"); }, grid = new Grid($element, gridOptions).render(); th = grid._headerRow.find("th").eq(0); th.trigger("click"); equal(grid._sortOrder, "asc"); equal(grid._sortField, grid.fields[0]); equal(grid.data[0].value, 1); equal(grid.data[1].value, 2); equal(grid.data[2].value, 3); ok(th.hasClass(grid.sortableClass)); ok(th.hasClass(grid.sortAscClass)); th.trigger("click"); equal(grid._sortOrder, "desc"); equal(grid._sortField, grid.fields[0]); equal(grid.data[0].value, 3); equal(grid.data[1].value, 2); equal(grid.data[2].value, 1); ok(!th.hasClass(grid.sortAscClass)); ok(th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, th, gridOptions = { sorting: true, 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"); grid = new Grid($element, gridOptions).render(); th = grid._headerRow.find("th").eq(0); th.trigger("click"); equal(grid._sortOrder, "asc"); equal(grid._sortField, grid.fields[0]); equal(loadFilter.sortOrder, "asc"); equal(loadFilter.sortField, "value"); th.trigger("click"); equal(grid._sortOrder, "desc"); equal(grid._sortField, grid.fields[0]); equal(loadFilter.sortOrder, "desc"); equal(loadFilter.sortField, "value"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"), th, gridOptions = { sorting: true, data: [ { value: 3 }, 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"); fields: [ { name: "value", sorting: false } ] }, grid = new Grid($element, gridOptions).render(); th = grid._headerRow.find("th").eq(0); th.trigger("click"); equal(grid._sortField, null); equal(grid.data[0].value, 3); equal(grid.data[1].value, 2); equal(grid.data[2].value, 1); ok(!th.hasClass(grid.sortAscClass)); }); }); }, 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> Tests: Code refactoring <DFF> @@ -24,20 +24,20 @@ $(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 right"); + deepEqual(grid.complexOption, gridOptions.complexOption, "object option copied correctly"); }); test("jquery adapter creation", function() { var gridOptions = { - option: "test" - }, + 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 transfered"); + 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() { @@ -49,11 +49,11 @@ $(function() { grid.destroy(); - strictEqual($element.html(), ""); - strictEqual($element.data(JSGRID_DATA_KEY), undefined); + strictEqual($element.html(), "", "content is removed"); + strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); - test("jquery adapter repeated call changes options", function() { + test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" @@ -70,7 +70,7 @@ $(function() { equal(grid.option, "new test", "option changed"); }); - test("jquery adapter invoke method", function() { + test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { @@ -95,11 +95,11 @@ $(function() { $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); - equal(testOption, "value"); + equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); - equal(testOption, "new_value"); + equal(testOption, "new_value", "set option value"); }); test("option changing event handlers", | 181 | Tests: Code refactoring | 181 | .js | tests | mit | tabalinas/jsgrid |
10064416 | <NME> jsgrid.css
<BEF> .jsgrid {
position: relative;
overflow: hidden;
font-size: 1em;
}
.jsgrid, .jsgrid *, .jsgrid *:before, .jsgrid *:after {
box-sizing: border-box;
}
.jsgrid input,
.jsgrid textarea,
.jsgrid select {
font-size: 1em;
}
.jsgrid-grid-header {
overflow-x: hidden;
overflow-y: scroll;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
.jsgrid-grid-body {
overflow-x: auto;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
.jsgrid-table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
border-spacing: 0;
}
.jsgrid-cell {
padding: 0.5em 0.5em;
}
.jsgrid-cell,
.jsgrid-header-cell {
box-sizing: border-box;
}
.jsgrid-align-left {
text-align: left;
}
.jsgrid-align-center,
.jsgrid-align-center input,
.jsgrid-align-center textarea,
.jsgrid-align-center select {
text-align: center;
}
.jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select,
.jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select {
width: 90%;
}
.jsgrid-filter-row input[type='checkbox'],
.jsgrid-header-cell {
padding: .5em .5em;
}
.jsgrid-filter-row input,
.jsgrid-filter-row textarea,
.jsgrid-filter-row select,
.jsgrid-edit-row input,
.jsgrid-edit-row textarea,
.jsgrid-edit-row select,
.jsgrid-insert-row input,
.jsgrid-insert-row textarea,
.jsgrid-insert-row select {
width: 100%;
padding: .3em .5em;
}
.jsgrid-filter-row input[type='checkbox'],
.jsgrid-edit-row input[type='checkbox'],
.jsgrid-insert-row input[type='checkbox'] {
width: auto;
}
.jsgrid-selected-row .jsgrid-cell {
cursor: pointer;
}
.jsgrid-nodata-row .jsgrid-cell {
padding: .5em 0;
text-align: center;
}
.jsgrid-header-sort {
cursor: pointer;
}
.jsgrid-pager {
padding: .5em 0;
}
.jsgrid-pager-nav-button {
padding: .2em .6em;
}
.jsgrid-pager-nav-inactive-button {
display: none;
pointer-events: none;
}
.jsgrid-pager-page {
padding: .2em .6em;
}
<MSG> Theme: Add editors padding
<DFF> @@ -60,6 +60,7 @@
.jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select,
.jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select {
width: 90%;
+ padding: .3em .5em;
}
.jsgrid-filter-row input[type='checkbox'],
| 1 | Theme: Add editors padding | 0 | .css | css | mit | tabalinas/jsgrid |
10064417 | <NME> jsgrid.css
<BEF> .jsgrid {
position: relative;
overflow: hidden;
font-size: 1em;
}
.jsgrid, .jsgrid *, .jsgrid *:before, .jsgrid *:after {
box-sizing: border-box;
}
.jsgrid input,
.jsgrid textarea,
.jsgrid select {
font-size: 1em;
}
.jsgrid-grid-header {
overflow-x: hidden;
overflow-y: scroll;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
.jsgrid-grid-body {
overflow-x: auto;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
}
.jsgrid-table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
border-spacing: 0;
}
.jsgrid-cell {
padding: 0.5em 0.5em;
}
.jsgrid-cell,
.jsgrid-header-cell {
box-sizing: border-box;
}
.jsgrid-align-left {
text-align: left;
}
.jsgrid-align-center,
.jsgrid-align-center input,
.jsgrid-align-center textarea,
.jsgrid-align-center select {
text-align: center;
}
.jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select,
.jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select {
width: 90%;
}
.jsgrid-filter-row input[type='checkbox'],
.jsgrid-header-cell {
padding: .5em .5em;
}
.jsgrid-filter-row input,
.jsgrid-filter-row textarea,
.jsgrid-filter-row select,
.jsgrid-edit-row input,
.jsgrid-edit-row textarea,
.jsgrid-edit-row select,
.jsgrid-insert-row input,
.jsgrid-insert-row textarea,
.jsgrid-insert-row select {
width: 100%;
padding: .3em .5em;
}
.jsgrid-filter-row input[type='checkbox'],
.jsgrid-edit-row input[type='checkbox'],
.jsgrid-insert-row input[type='checkbox'] {
width: auto;
}
.jsgrid-selected-row .jsgrid-cell {
cursor: pointer;
}
.jsgrid-nodata-row .jsgrid-cell {
padding: .5em 0;
text-align: center;
}
.jsgrid-header-sort {
cursor: pointer;
}
.jsgrid-pager {
padding: .5em 0;
}
.jsgrid-pager-nav-button {
padding: .2em .6em;
}
.jsgrid-pager-nav-inactive-button {
display: none;
pointer-events: none;
}
.jsgrid-pager-page {
padding: .2em .6em;
}
<MSG> Theme: Add editors padding
<DFF> @@ -60,6 +60,7 @@
.jsgrid-edit-row input, .jsgrid-edit-row textarea, .jsgrid-edit-row select,
.jsgrid-insert-row input, .jsgrid-insert-row textarea, .jsgrid-insert-row select {
width: 90%;
+ padding: .3em .5em;
}
.jsgrid-filter-row input[type='checkbox'],
| 1 | Theme: Add editors padding | 0 | .css | css | mit | tabalinas/jsgrid |
10064418 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064419 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064420 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064421 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064422 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064423 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064424 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064425 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064426 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064427 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064428 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064429 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064430 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064431 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064432 | <NME> MainWindow.xaml
<BEF> <Window xmlns="https://github.com/avaloniaui"
xmlns:AvalonEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinWidth="0"
MinHeight="300"
Width="950"
Title="AvaloniaEdit Demo"
x:Class="AvaloniaEdit.Demo.MainWindow"
Background="#1E1E1E">
<DockPanel>
<StackPanel Orientation="Horizontal"
DockPanel.Dock="Top"
Spacing="5"
Margin="3">
<ToggleButton Name="wordWrap" ToolTip.Tip="Word wrap" IsChecked="{Binding #Editor.WordWrap}">
<ToggleButton.Content>
<Path Fill="White" Data="M2.75 5C2.33579 5 2 5.33579 2 5.75C2 6.16421 2.33579 6.5 2.75 6.5H21.25C21.6642 6.5 22 6.16421 22 5.75C22 5.33579 21.6642 5 21.25 5H2.75Z M2.75 11.5C2.33579 11.5 2 11.8358 2 12.25C2 12.6642 2.33579 13 2.75 13H19C20.3807 13 21.5 14.1193 21.5 15.5C21.5 16.8807 20.3807 18 19 18H14.5607L15.2803 17.2803C15.5732 16.9874 15.5732 16.5126 15.2803 16.2197C14.9874 15.9268 14.5126 15.9268 14.2197 16.2197L12.2197 18.2197C11.9268 18.5126 11.9268 18.9874 12.2197 19.2803L14.2197 21.2803C14.5126 21.5732 14.9874 21.5732 15.2803 21.2803C15.5732 20.9874 15.5732 20.5126 15.2803 20.2197L14.5607 19.5H19C21.2091 19.5 23 17.7091 23 15.5C23 13.2909 21.2091 11.5 19 11.5H2.75Z M2 18.75C2 18.3358 2.33579 18 2.75 18H9.25C9.66421 18 10 18.3358 10 18.75C10 19.1642 9.66421 19.5 9.25 19.5H2.75C2.33579 19.5 2 19.1642 2 18.75Z" />
</ToggleButton.Content>
</ToggleButton>
<ToggleButton Name="viewTabs" Content="View tabs" IsChecked="{Binding #Editor.Options.ShowTabs}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewSpaces" Content="View spaces" IsChecked="{Binding #Editor.Options.ShowSpaces}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewEOL" Content="View EOL" IsChecked="{Binding #Editor.Options.ShowEndOfLine}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ToggleButton Name="viewColumnRules" Content="View columns rulers" IsChecked="{Binding #Editor.Options.ShowColumnRulers}" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="addControlBtn" Content="Add Button" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="clearControlBtn" Content="Clear Buttons" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<ComboBox Name="syntaxModeCombo" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
<Button Name="changeThemeBtn" Content="Change theme" VerticalAlignment="Stretch" VerticalContentAlignment="Center"/>
</StackPanel>
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
FontFamily="Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Visible"
FontWeight="Light"
FontSize="14" />
</DockPanel>
</Window>
<MSG> Enable Cascadia Code font (if available) to enable font ligatures
<DFF> @@ -29,7 +29,7 @@
<TextBlock Name="StatusText" Text="Ready" Margin="5 0 0 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
<AvalonEdit:TextEditor Name="Editor"
- FontFamily="Consolas,Menlo,Monospace"
+ FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
Margin="30"
Foreground="#D4D4D4"
HorizontalScrollBarVisibility="Auto"
| 1 | Enable Cascadia Code font (if available) to enable font ligatures | 1 | .xaml | Demo/MainWindow | mit | AvaloniaUI/AvaloniaEdit |
10064433 | <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() {
$bodyGridTable;
ok($element.hasClass(grid.containerClass), "container class attached");
equal($element.children().length, 3);
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");
{ 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: Create loading indicator on render
<DFF> @@ -145,7 +145,6 @@ $(function() {
$bodyGridTable;
ok($element.hasClass(grid.containerClass), "container class attached");
- equal($element.children().length, 3);
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");
| 0 | Core: Create loading indicator on render | 1 | .js | tests | mit | tabalinas/jsgrid |
10064434 | <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() {
$bodyGridTable;
ok($element.hasClass(grid.containerClass), "container class attached");
equal($element.children().length, 3);
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");
{ 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: Create loading indicator on render
<DFF> @@ -145,7 +145,6 @@ $(function() {
$bodyGridTable;
ok($element.hasClass(grid.containerClass), "container class attached");
- equal($element.children().length, 3);
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");
| 0 | Core: Create loading indicator on render | 1 | .js | tests | mit | tabalinas/jsgrid |
10064435 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064436 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064437 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064438 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064439 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064440 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064441 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064442 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064443 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064444 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064445 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064446 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064447 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064448 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
|
10064449 | <NME> .gitattributes
<BEF> ADDFILE
<MSG> Merge remote-tracking branch 'aelij/master'
<DFF> @@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
| 63 | Merge remote-tracking branch 'aelij/master' | 0 | gitattributes | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.