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
|
---|---|---|---|---|---|---|---|---|
10062550 | <NME> VisualLineLinkText.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 AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Merge pull request #157 from AvaloniaUI/feature/textmate-support
Textmate grammars support
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Merge pull request #157 from AvaloniaUI/feature/textmate-support | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062551 | <NME> VisualLineLinkText.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 AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Merge pull request #157 from AvaloniaUI/feature/textmate-support
Textmate grammars support
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Merge pull request #157 from AvaloniaUI/feature/textmate-support | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062552 | <NME> VisualLineLinkText.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 AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Merge pull request #157 from AvaloniaUI/feature/textmate-support
Textmate grammars support
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Merge pull request #157 from AvaloniaUI/feature/textmate-support | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062553 | <NME> VisualLineLinkText.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 AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Merge pull request #157 from AvaloniaUI/feature/textmate-support
Textmate grammars support
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Merge pull request #157 from AvaloniaUI/feature/textmate-support | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062554 | <NME> VisualLineLinkText.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 AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Merge pull request #157 from AvaloniaUI/feature/textmate-support
Textmate grammars support
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Merge pull request #157 from AvaloniaUI/feature/textmate-support | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062555 | <NME> VisualLineLinkText.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 AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Merge pull request #157 from AvaloniaUI/feature/textmate-support
Textmate grammars support
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Merge pull request #157 from AvaloniaUI/feature/textmate-support | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062556 | <NME> VisualLineLinkText.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 AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Merge pull request #157 from AvaloniaUI/feature/textmate-support
Textmate grammars support
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Merge pull request #157 from AvaloniaUI/feature/textmate-support | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062557 | <NME> VisualLineLinkText.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 AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Merge pull request #157 from AvaloniaUI/feature/textmate-support
Textmate grammars support
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Merge pull request #157 from AvaloniaUI/feature/textmate-support | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062558 | <NME> VisualLineLinkText.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 AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
namespace AvaloniaEdit.Rendering
{
{
/// <summary>
/// </summary>
public class VisualLineLinkText : VisualLineText
{
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
/// Routed event that should navigate to uri when the link is clicked.
/// </summary>
public static RoutedEvent<OpenUriRoutedEventArgs> OpenUriEvent { get; } = RoutedEvent.Register<VisualLineText,OpenUriRoutedEventArgs>(nameof(OpenUriEvent), RoutingStrategies.Bubble);
/// <summary>
/// Gets/Sets the URL that is navigated to when the link is clicked.
/// </summary>
public Uri NavigateUri { get; set; }
/// <summary>
/// Gets/Sets the window name where the URL will be opened.
/// </summary>
public string TargetName { get; set; }
/// <summary>
/// Gets/Sets whether the user needs to press Control to click the link.
/// The default value is true.
/// </summary>
public bool RequireControlModifierForClick { get; set; }
/// <summary>
/// Creates a visual line text element with the specified length.
/// It uses the <see cref="ITextRunConstructionContext.VisualLine"/> and its
/// <see cref="VisualLineElement.RelativeTextOffset"/> to find the actual text string.
/// </summary>
public VisualLineLinkText(VisualLine parentVisualLine, int length) : base(parentVisualLine, length)
{
RequireControlModifierForClick = true;
}
/// <inheritdoc/>
public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context)
{
this.TextRunProperties.SetForegroundBrush(context.TextView.LinkTextForegroundBrush);
this.TextRunProperties.SetBackgroundBrush(context.TextView.LinkTextBackgroundBrush);
if (context.TextView.LinkTextUnderline)
this.TextRunProperties.SetTextDecorations(TextDecorations.Underline);
return base.CreateTextRun(startVisualColumn, context);
}
/// <summary>
/// Gets whether the link is currently clickable.
/// </summary>
/// <remarks>Returns true when control is pressed; or when
/// <see cref="RequireControlModifierForClick"/> is disabled.</remarks>
protected virtual bool LinkIsClickable(KeyModifiers modifiers)
{
if (NavigateUri == null)
return false;
if (RequireControlModifierForClick)
return modifiers.HasFlag(KeyModifiers.Control);
return true;
}
/// <inheritdoc/>
protected internal override void OnQueryCursor(PointerEventArgs e)
{
if (LinkIsClickable(e.KeyModifiers))
{
if(e.Source is InputElement inputElement)
{
inputElement.Cursor = new Cursor(StandardCursorType.Hand);
}
e.Handled = true;
}
}
/// <inheritdoc/>
protected internal override void OnPointerPressed(PointerPressedEventArgs e)
{
if (!e.Handled && LinkIsClickable(e.KeyModifiers))
{
var eventArgs = new OpenUriRoutedEventArgs(NavigateUri) { RoutedEvent = OpenUriEvent };
e.Source.RaiseEvent(eventArgs);
e.Handled = true;
}
}
/// <inheritdoc/>
protected override VisualLineText CreateInstance(int length)
{
return new VisualLineLinkText(ParentVisualLine, length)
RequireControlModifierForClick = RequireControlModifierForClick
};
}
}
/// <summary>
/// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
/// </summary>
/// <example>
/// This sample shows how to open link using system's web brower
/// <code>
/// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
/// var link = args.Uri.ToString();
/// try
/// {
/// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
/// {
/// Process.Start(link);
/// }
/// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
/// {
/// Process.Start("open", link);
/// }
/// else
/// {
/// Process.Start("xdg-open", link);
/// }
/// }
/// catch (Exception)
/// {
/// // Process.Start can throw several errors (not all of them documented),
/// // just ignore all of them.
/// }
/// }
/// });
/// </code>
/// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
public OpenUriRoutedEventArgs(Uri uri)
{
Uri = uri ?? throw new ArgumentNullException(nameof(uri));
}
}
}
<MSG> Merge pull request #157 from AvaloniaUI/feature/textmate-support
Textmate grammars support
<DFF> @@ -20,6 +20,8 @@ using System;
using AvaloniaEdit.Text;
using Avalonia.Input;
using Avalonia.Interactivity;
+using Avalonia.Controls;
+using System.Diagnostics;
namespace AvaloniaEdit.Rendering
{
@@ -28,6 +30,10 @@ namespace AvaloniaEdit.Rendering
/// </summary>
public class VisualLineLinkText : VisualLineText
{
+ static VisualLineLinkText()
+ {
+ OpenUriEvent.AddClassHandler<Window>(ExecuteOpenUriEventHandler);
+ }
/// <summary>
/// Routed event that should navigate to uri when the link is clicked.
@@ -116,40 +122,29 @@ namespace AvaloniaEdit.Rendering
RequireControlModifierForClick = RequireControlModifierForClick
};
}
+
+ static Action<OpenUriRoutedEventArgs> ExecuteOpenUriEventHandler(Window window)
+ {
+ return arg =>
+ {
+ var url = arg.Uri.ToString();
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception)
+ {
+ // Process.Start can throw several errors (not all of them documented),
+ // just ignore all of them.
+ }
+ };
+ }
}
- /// <summary>
- /// Holds arguments for a <see cref="VisualLineLinkText.OpenUriEvent"/>.
- /// </summary>
- /// <example>
- /// This sample shows how to open link using system's web brower
- /// <code>
- /// VisualLineLinkText.OpenUriEvent.AddClassHandler<Window>(args => {
- /// var link = args.Uri.ToString();
- /// try
- /// {
- /// if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- /// {
- /// Process.Start(link);
- /// }
- /// else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- /// {
- /// Process.Start("open", link);
- /// }
- /// else
- /// {
- /// Process.Start("xdg-open", link);
- /// }
- /// }
- /// catch (Exception)
- /// {
- /// // Process.Start can throw several errors (not all of them documented),
- /// // just ignore all of them.
- /// }
- /// }
- /// });
- /// </code>
- /// </example>
public sealed class OpenUriRoutedEventArgs : RoutedEventArgs
{
public Uri Uri { get; }
| 27 | Merge pull request #157 from AvaloniaUI/feature/textmate-support | 32 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062559 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062560 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062561 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062562 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062563 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062564 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062565 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062566 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062567 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062568 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062569 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062570 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062571 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062572 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062573 | <NME> ExtensionMethods.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.
extern alias SystemDrawing;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
using SystemDrawingColor = global::System.Drawing;
namespace AvaloniaEdit.Utils
{
namespace AvaloniaEdit.Utils
{
public static class ExtensionMethods
{
#region Epsilon / IsClose / CoerceValue
/// <summary>
/// Epsilon used for <c>IsClose()</c> implementations.
/// We can use up quite a few digits in front of the decimal point (due to visual positions being relative to document origin),
/// and there's no need to be too accurate (we're dealing with pixels here),
/// so we will use the value 0.01.
/// Previosly we used 1e-8 but that was causing issues:
/// https://community.sharpdevelop.net/forums/t/16048.aspx
/// </summary>
public const double Epsilon = 0.01;
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this double d1, double d2)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (d1 == d2) // required for infinities
return true;
return Math.Abs(d1 - d2) < Epsilon;
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Size d1, Size d2)
{
return IsClose(d1.Width, d2.Width) && IsClose(d1.Height, d2.Height);
}
/// <summary>
/// Returns true if the doubles are close (difference smaller than 0.01).
/// </summary>
public static bool IsClose(this Vector d1, Vector d2)
{
return IsClose(d1.X, d2.X) && IsClose(d1.Y, d2.Y);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static double CoerceValue(this double value, double minimum, double maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
/// <summary>
/// Forces the value to stay between mininum and maximum.
/// </summary>
/// <returns>minimum, if value is less than minimum.
/// Maximum, if value is greater than maximum.
/// Otherwise, value.</returns>
public static int CoerceValue(this int value, int minimum, int maximum)
{
return Math.Max(Math.Min(value, maximum), minimum);
}
#endregion
#region CreateTypeface
/// <summary>
/// Creates typeface from the framework element.
/// </summary>
public static Typeface CreateTypeface(this Control fe)
{
return new Typeface(fe.GetValue(TextElement.FontFamilyProperty),
fe.GetValue(TextElement.FontStyleProperty),
fe.GetValue(TextElement.FontWeightProperty),
fe.GetValue(TextElement.FontStretchProperty));
}
#endregion
#region AddRange / Sequence
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> elements)
{
foreach (T e in elements)
collection.Add(e);
}
/// <summary>
/// Creates an IEnumerable with a single value.
/// </summary>
public static IEnumerable<T> Sequence<T>(T value)
{
yield return value;
}
#endregion
#region XML reading
///// <summary>
///// Gets the value of the attribute, or null if the attribute does not exist.
///// </summary>
//public static string GetAttributeOrNull(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? attr.Value : null;
//}
///// <summary>
///// Gets the value of the attribute as boolean, or null if the attribute does not exist.
///// </summary>
//public static bool? GetBoolAttribute(this XmlElement element, string attributeName)
//{
// XmlAttribute attr = element.GetAttributeNode(attributeName);
// return attr != null ? (bool?)XmlConvert.ToBoolean(attr.Value) : null;
//}
/// <summary>
/// Gets the value of the attribute as boolean, or null if the attribute does not exist.
/// </summary>
public static bool? GetBoolAttribute(this XmlReader reader, string attributeName)
{
string attributeValue = reader.GetAttribute(attributeName);
if (attributeValue == null)
return null;
else
return XmlConvert.ToBoolean(attributeValue);
}
#endregion
#region DPI independence
//public static Rect TransformToDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Rect TransformFromDevice(this Rect rect, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice;
// return Rect.Transform(rect, matrix);
//}
//public static Size TransformToDevice(this Size size, Visual visual)
//{
// Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;
// return new Size(size.Width * matrix.M11, size.Height * matrix.M22);
//}
//public static Size TransformFromDevice(this Size size, Visual visual)
#endregion
#region System.Drawing <-> Avalonia conversions
public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
{
return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
}
public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
#endregion
#region Snap to device pixels
public static Point SnapToDevicePixels(this Point p, IVisual targetVisual)
{
var root = targetVisual.GetVisualRoot();
// Get the root control and its scaling
var scaling = new Vector(root.RenderScaling, root.RenderScaling);
// Create a matrix to translate from control coordinates to device coordinates.
var m = targetVisual.TransformToVisual((Control)root) * Matrix.CreateScale(scaling);
if (m == null)
return p;
// Translate the point to device coordinates.
var devicePoint = p.Transform(m.Value);
// Snap the coordinate to the midpoint between device pixels.
devicePoint = new Point(((int)devicePoint.X) + 0.5, ((int)devicePoint.Y) + 0.5);
// Translate the point back to control coordinates.
var inv = m.Value.Invert();
Point result = devicePoint.Transform(inv);
return result;
}
#endregion
public static IEnumerable<AvaloniaObject> VisualAncestorsAndSelf(this AvaloniaObject obj)
{
while (obj != null)
{
yield return obj;
if (obj is Visual v)
{
obj = (AvaloniaObject)v.GetVisualParent();
}
else
{
break;
}
}
}
public static IEnumerable<char> AsEnumerable(this string s)
{
// ReSharper disable once ForCanBeConvertedToForeach
for (var i = 0; i < s.Length; i++)
{
yield return s[i];
}
}
[Conditional("DEBUG")]
public static void CheckIsFrozen(object o)
{
if (o is IFreezable f && !f.IsFrozen)
Debug.WriteLine("Performance warning: Not frozen: " + f);
}
[Conditional("DEBUG")]
public static void Log(bool condition, string format, params object[] args)
{
if (condition)
{
string output = DateTime.Now.ToString("hh:MM:ss") + ": " + string.Format(format, args); //+ Environment.NewLine + Environment.StackTrace;
//Console.WriteLine(output);
Debug.WriteLine(output);
}
}
public static bool CapturePointer(this IInputElement element, IPointer device)
{
device.Capture(element);
return device.Captured == element;
}
public static void ReleasePointerCapture(this IInputElement element, IPointer device)
{
if (element == device.Captured)
{
device.Capture(null);
}
}
public static T PeekOrDefault<T>(this ImmutableStack<T> stack)
{
return stack.IsEmpty ? default(T) : stack.Peek();
}
}
}
<MSG> compatibility with latest avalonia
<DFF> @@ -15,8 +15,6 @@
// 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.
-extern alias SystemDrawing;
-
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -25,8 +23,6 @@ using System.Xml;
using Avalonia;
using Avalonia.Input;
using Avalonia.VisualTree;
-using SystemDrawingColor = global::System.Drawing;
-
namespace AvaloniaEdit.Utils
{
@@ -180,22 +176,23 @@ namespace AvaloniaEdit.Utils
#endregion
#region System.Drawing <-> Avalonia conversions
- public static SystemDrawing::System.Drawing.Point ToSystemDrawing(this Point p)
+ public static System.Drawing.Point ToSystemDrawing(this Point p)
{
- return new SystemDrawing::System.Drawing.Point((int)p.X, (int)p.Y);
+ return new System.Drawing.Point((int)p.X, (int)p.Y);
+
}
- public static Point ToAvalonia(this SystemDrawing::System.Drawing.Point p)
+ public static Point ToAvalonia(this System.Drawing.Point p)
{
return new Point(p.X, p.Y);
}
- public static Size ToAvalonia(this SystemDrawing::System.Drawing.Size s)
+ public static Size ToAvalonia(this System.Drawing.Size s)
{
return new Size(s.Width, s.Height);
}
- public static Rect ToAvalonia(this SystemDrawing::System.Drawing.Rectangle rect)
+ public static Rect ToAvalonia(this System.Drawing.Rectangle rect)
{
return new Rect(rect.Location.ToAvalonia(), rect.Size.ToAvalonia());
}
| 6 | compatibility with latest avalonia | 9 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062574 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062575 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062576 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062577 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062578 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062579 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062580 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062581 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062582 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062583 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062584 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062585 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062586 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062587 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062588 | <NME> ThemeName.cs
<BEF> ADDFILE
<MSG> Added grammars and themes to AvaloniaEdit.TextMate project
<DFF> @@ -0,0 +1,19 @@
+namespace AvaloniaEdit.TextMate
+{
+ public enum ThemeName
+ {
+ Abbys,
+ Dark,
+ DarkPlus,
+ DimmedMonokai,
+ KimbieDark,
+ Light,
+ LightPlus,
+ Monokai,
+ QuietLight,
+ Red,
+ SolarizedDark,
+ SolarizedLight,
+ TomorrowNightBlue,
+ }
+}
| 19 | Added grammars and themes to AvaloniaEdit.TextMate project | 0 | .cs | TextMate/ThemeName | mit | AvaloniaUI/AvaloniaEdit |
10062589 | <NME> pt-BR
<BEF> ADDFILE
<MSG> Merge pull request #206 from jefferson/patch-1
i18n: Add pt-BR localization
<DFF> @@ -0,0 +1,46 @@
+(function(jsGrid) {
+
+ jsGrid.locales.pt_BR = {
+ grid: {
+ noDataContent: "Não encontrado",
+ deleteConfirm: "Você tem certeza que deseja remover este item?",
+ pagerFormat: "Páginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
+ pagePrevText: "Anterior",
+ pageNextText: "Seguinte",
+ pageFirstText: "Primeira",
+ pageLastText: "Última",
+ loadMessage: "Por favor, espere...",
+ invalidMessage: "Dados inválidos!"
+ },
+
+ loadIndicator: {
+ message: "Carregando..."
+ },
+
+ fields: {
+ control: {
+ searchModeButtonTooltip: "Mudar para busca",
+ insertModeButtonTooltip: "Mudar para inserção",
+ editButtonTooltip: "Editar",
+ deleteButtonTooltip: "Remover",
+ searchButtonTooltip: "Buscar",
+ clearFilterButtonTooltip: "Remover filtro",
+ insertButtonTooltip: "Adicionar",
+ updateButtonTooltip: "Atualizar",
+ cancelEditButtonTooltip: "Cancelar Edição"
+ }
+ },
+
+ validators: {
+ required: { message: "Campo obrigatório" },
+ rangeLength: { message: "O valor esta fora do intervaldo definido" },
+ minLength: { message: "O comprimento do valor é muito longo" },
+ maxLength: { message: "O comprimento valor é muito curto" },
+ pattern: { message: "O valor informado não é compatível com o padrão" },
+ range: { message: "O valor informado esta fora do limite definido" },
+ min: { message: "O valor é muito longo" },
+ max: { message: "O valor é muito curto" }
+ }
+ };
+
+}(jsGrid, jQuery));
| 46 | Merge pull request #206 from jefferson/patch-1 | 0 | pt-BR | mit | tabalinas/jsgrid |
|
10062590 | <NME> pt-BR
<BEF> ADDFILE
<MSG> Merge pull request #206 from jefferson/patch-1
i18n: Add pt-BR localization
<DFF> @@ -0,0 +1,46 @@
+(function(jsGrid) {
+
+ jsGrid.locales.pt_BR = {
+ grid: {
+ noDataContent: "Não encontrado",
+ deleteConfirm: "Você tem certeza que deseja remover este item?",
+ pagerFormat: "Páginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
+ pagePrevText: "Anterior",
+ pageNextText: "Seguinte",
+ pageFirstText: "Primeira",
+ pageLastText: "Última",
+ loadMessage: "Por favor, espere...",
+ invalidMessage: "Dados inválidos!"
+ },
+
+ loadIndicator: {
+ message: "Carregando..."
+ },
+
+ fields: {
+ control: {
+ searchModeButtonTooltip: "Mudar para busca",
+ insertModeButtonTooltip: "Mudar para inserção",
+ editButtonTooltip: "Editar",
+ deleteButtonTooltip: "Remover",
+ searchButtonTooltip: "Buscar",
+ clearFilterButtonTooltip: "Remover filtro",
+ insertButtonTooltip: "Adicionar",
+ updateButtonTooltip: "Atualizar",
+ cancelEditButtonTooltip: "Cancelar Edição"
+ }
+ },
+
+ validators: {
+ required: { message: "Campo obrigatório" },
+ rangeLength: { message: "O valor esta fora do intervaldo definido" },
+ minLength: { message: "O comprimento do valor é muito longo" },
+ maxLength: { message: "O comprimento valor é muito curto" },
+ pattern: { message: "O valor informado não é compatível com o padrão" },
+ range: { message: "O valor informado esta fora do limite definido" },
+ min: { message: "O valor é muito longo" },
+ max: { message: "O valor é muito curto" }
+ }
+ };
+
+}(jsGrid, jQuery));
| 46 | Merge pull request #206 from jefferson/patch-1 | 0 | pt-BR | mit | tabalinas/jsgrid |
|
10062591 | <NME> es.js
<BEF> (function(jsGrid) {
jsGrid.locales.es = {
grid: {
noDataContent: "No encontrado",
deleteConfirm: "Esta seguro?",
pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "Anterior",
pageNextText: "Siguiente",
pageFirstText: "Primero",
pageLastText: "Ultimo",
loadMessage: "Espere, por favor...",
invalidMessage: "Datos inválidos!"
},
loadIndicator: {
message: "Cargando..."
},
fields: {
control: {
searchModeButtonTooltip: "Cambia a búsqueda",
insertModeButtonTooltip: "Cambia a inserción",
editButtonTooltip: "Editar",
deleteButtonTooltip: "Suprimir",
searchButtonTooltip: "Buscar",
clearFilterButtonTooltip: "Borrar filtro",
insertButtonTooltip: "Insertar",
updateButtonTooltip: "Actualizar",
cancelEditButtonTooltip: "Cancelar edición"
}
},
validators: {
required: { message: "Campo requerido" },
rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" },
minLength: { message: "La longitud del valor esta demasiado largo" },
maxLength: { message: "La longitud del valor esta demasiado corto" },
pattern: { message: "Valor no coincide con el patrón definido" },
range: { message: "Valor fuera del intervalo definido" },
min: { message: "Valor demasiado alto" },
max: { message: "Valor demasiado bajo" }
}
};
}(jsGrid, jQuery));
<MSG> Merge pull request #186 from julmarci/julmarci
i18n: Spanish localization improvements
<DFF> @@ -3,14 +3,14 @@
jsGrid.locales.es = {
grid: {
noDataContent: "No encontrado",
- deleteConfirm: "Esta seguro?",
+ deleteConfirm: "¿Está seguro?",
pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "Anterior",
pageNextText: "Siguiente",
pageFirstText: "Primero",
pageLastText: "Ultimo",
- loadMessage: "Espere, por favor...",
- invalidMessage: "Datos inválidos!"
+ loadMessage: "Por favor, espere...",
+ invalidMessage: "¡Datos no válidos!"
},
loadIndicator: {
@@ -19,8 +19,8 @@
fields: {
control: {
- searchModeButtonTooltip: "Cambia a búsqueda",
- insertModeButtonTooltip: "Cambia a inserción",
+ searchModeButtonTooltip: "Cambiar a búsqueda",
+ insertModeButtonTooltip: "Cambiar a inserción",
editButtonTooltip: "Editar",
deleteButtonTooltip: "Suprimir",
searchButtonTooltip: "Buscar",
@@ -33,11 +33,11 @@
validators: {
required: { message: "Campo requerido" },
- rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" },
- minLength: { message: "La longitud del valor esta demasiado largo" },
- maxLength: { message: "La longitud del valor esta demasiado corto" },
- pattern: { message: "Valor no coincide con el patrón definido" },
- range: { message: "Valor fuera del intervalo definido" },
+ rangeLength: { message: "La longitud del valor está fuera del intervalo definido" },
+ minLength: { message: "La longitud del valor es demasiado larga" },
+ maxLength: { message: "La longitud del valor es demasiado corta" },
+ pattern: { message: "El valor no se ajusta al patrón definido" },
+ range: { message: "Valor fuera del rango definido" },
min: { message: "Valor demasiado alto" },
max: { message: "Valor demasiado bajo" }
}
| 10 | Merge pull request #186 from julmarci/julmarci | 10 | .js | js | mit | tabalinas/jsgrid |
10062592 | <NME> es.js
<BEF> (function(jsGrid) {
jsGrid.locales.es = {
grid: {
noDataContent: "No encontrado",
deleteConfirm: "Esta seguro?",
pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "Anterior",
pageNextText: "Siguiente",
pageFirstText: "Primero",
pageLastText: "Ultimo",
loadMessage: "Espere, por favor...",
invalidMessage: "Datos inválidos!"
},
loadIndicator: {
message: "Cargando..."
},
fields: {
control: {
searchModeButtonTooltip: "Cambia a búsqueda",
insertModeButtonTooltip: "Cambia a inserción",
editButtonTooltip: "Editar",
deleteButtonTooltip: "Suprimir",
searchButtonTooltip: "Buscar",
clearFilterButtonTooltip: "Borrar filtro",
insertButtonTooltip: "Insertar",
updateButtonTooltip: "Actualizar",
cancelEditButtonTooltip: "Cancelar edición"
}
},
validators: {
required: { message: "Campo requerido" },
rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" },
minLength: { message: "La longitud del valor esta demasiado largo" },
maxLength: { message: "La longitud del valor esta demasiado corto" },
pattern: { message: "Valor no coincide con el patrón definido" },
range: { message: "Valor fuera del intervalo definido" },
min: { message: "Valor demasiado alto" },
max: { message: "Valor demasiado bajo" }
}
};
}(jsGrid, jQuery));
<MSG> Merge pull request #186 from julmarci/julmarci
i18n: Spanish localization improvements
<DFF> @@ -3,14 +3,14 @@
jsGrid.locales.es = {
grid: {
noDataContent: "No encontrado",
- deleteConfirm: "Esta seguro?",
+ deleteConfirm: "¿Está seguro?",
pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} {pageIndex} de {pageCount}",
pagePrevText: "Anterior",
pageNextText: "Siguiente",
pageFirstText: "Primero",
pageLastText: "Ultimo",
- loadMessage: "Espere, por favor...",
- invalidMessage: "Datos inválidos!"
+ loadMessage: "Por favor, espere...",
+ invalidMessage: "¡Datos no válidos!"
},
loadIndicator: {
@@ -19,8 +19,8 @@
fields: {
control: {
- searchModeButtonTooltip: "Cambia a búsqueda",
- insertModeButtonTooltip: "Cambia a inserción",
+ searchModeButtonTooltip: "Cambiar a búsqueda",
+ insertModeButtonTooltip: "Cambiar a inserción",
editButtonTooltip: "Editar",
deleteButtonTooltip: "Suprimir",
searchButtonTooltip: "Buscar",
@@ -33,11 +33,11 @@
validators: {
required: { message: "Campo requerido" },
- rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" },
- minLength: { message: "La longitud del valor esta demasiado largo" },
- maxLength: { message: "La longitud del valor esta demasiado corto" },
- pattern: { message: "Valor no coincide con el patrón definido" },
- range: { message: "Valor fuera del intervalo definido" },
+ rangeLength: { message: "La longitud del valor está fuera del intervalo definido" },
+ minLength: { message: "La longitud del valor es demasiado larga" },
+ maxLength: { message: "La longitud del valor es demasiado corta" },
+ pattern: { message: "El valor no se ajusta al patrón definido" },
+ range: { message: "Valor fuera del rango definido" },
min: { message: "Valor demasiado alto" },
max: { message: "Valor demasiado bajo" }
}
| 10 | Merge pull request #186 from julmarci/julmarci | 10 | .js | js | mit | tabalinas/jsgrid |
10062593 | <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();
strictEqual(grid._sortOrder, "asc", "sortOrder reset");
});
module("filtering");
}
}
},
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> Option: Support loadStrategy change on the fly
<DFF> @@ -407,6 +407,42 @@ $(function() {
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");
| 36 | Option: Support loadStrategy change on the fly | 0 | .js | tests | mit | tabalinas/jsgrid |
10062594 | <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();
strictEqual(grid._sortOrder, "asc", "sortOrder reset");
});
module("filtering");
}
}
},
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> Option: Support loadStrategy change on the fly
<DFF> @@ -407,6 +407,42 @@ $(function() {
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");
| 36 | Option: Support loadStrategy change on the fly | 0 | .js | tests | mit | tabalinas/jsgrid |
10062595 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
},
_refreshWidth: function() {
var $headerGrid = this._headerGrid,
$bodyGrid = this._bodyGrid,
width = this.width;
if(width === "auto") {
$headerGrid.width("auto");
width = $headerGrid.outerWidth();
}
$headerGrid.width("");
$bodyGrid.width("");
this._container.width(width);
width = $headerGrid.outerWidth();
$bodyGrid.width(width);
},
_scrollBarWidth: (function() {
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Core: Prevent grid from shrinking on refresh when with 'auto'
Fixes #307
<DFF> @@ -901,20 +901,23 @@
},
_refreshWidth: function() {
+ var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
+
+ this._container.width(width);
+ },
+
+ _getAutoWidth: function() {
var $headerGrid = this._headerGrid,
- $bodyGrid = this._bodyGrid,
- width = this.width;
+ $header = this._header;
- if(width === "auto") {
- $headerGrid.width("auto");
- width = $headerGrid.outerWidth();
- }
+ $headerGrid.width("auto");
+
+ var contentWidth = $headerGrid.outerWidth();
+ var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
- $bodyGrid.width("");
- this._container.width(width);
- width = $headerGrid.outerWidth();
- $bodyGrid.width(width);
+
+ return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
| 13 | Core: Prevent grid from shrinking on refresh when with 'auto' | 10 | .js | core | mit | tabalinas/jsgrid |
10062596 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
if($.isFunction(this.rowRenderer)) {
$result = this.renderTemplate(this.rowRenderer, this, { item: item, itemIndex: itemIndex });
} else {
$result = $("<tr>");
this._renderCells($result, item);
}
$result.addClass(this._getRowClasses(item, itemIndex))
.data(JSGRID_ROW_DATA_KEY, item)
.on("click", $.proxy(function(e) {
this.rowClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this))
.on("dblclick", $.proxy(function(e) {
this.rowDoubleClick({
item: item,
itemIndex: itemIndex,
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
},
_refreshWidth: function() {
var $headerGrid = this._headerGrid,
$bodyGrid = this._bodyGrid,
width = this.width;
if(width === "auto") {
$headerGrid.width("auto");
width = $headerGrid.outerWidth();
}
$headerGrid.width("");
$bodyGrid.width("");
this._container.width(width);
width = $headerGrid.outerWidth();
$bodyGrid.width(width);
},
_scrollBarWidth: (function() {
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var result = [];
if (includeHeaders){
var fieldsLength = this.fields.length;
var fieldNames = {};
for(var i=0;i<fieldsLength;i++){
var field = this.fields[i];
if ("includeInDataExport" in field){
if (field.includeInDataExport === true)
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Core: Prevent grid from shrinking on refresh when with 'auto'
Fixes #307
<DFF> @@ -901,20 +901,23 @@
},
_refreshWidth: function() {
+ var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
+
+ this._container.width(width);
+ },
+
+ _getAutoWidth: function() {
var $headerGrid = this._headerGrid,
- $bodyGrid = this._bodyGrid,
- width = this.width;
+ $header = this._header;
- if(width === "auto") {
- $headerGrid.width("auto");
- width = $headerGrid.outerWidth();
- }
+ $headerGrid.width("auto");
+
+ var contentWidth = $headerGrid.outerWidth();
+ var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
- $bodyGrid.width("");
- this._container.width(width);
- width = $headerGrid.outerWidth();
- $bodyGrid.width(width);
+
+ return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
| 13 | Core: Prevent grid from shrinking on refresh when with 'auto' | 10 | .js | core | mit | tabalinas/jsgrid |
10062597 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = item[field.name];
if($.isFunction(field.cellRenderer)) {
$result = $(field.cellRenderer(fieldValue, item));
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
$("<td>").addClass(field.editcss || field.css)
.appendTo($result)
.append(field.editTemplate ? field.editTemplate(item[field.name], item) : "")
.width(field.width || "auto");
});
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Merge pull request #165 from ZainShaikh/master
Core: Support dot notation for properties binding
<DFF> @@ -606,9 +606,20 @@
return this;
},
+ _getFieldValue: function(item, name, field) {
+ var props = name.split('.');
+ var fieldValue = item[props.shift()];
+
+ while (props.length > 0) {
+ fieldValue = fieldValue[props.shift()];
+ }
+
+ return fieldValue;
+ },
+
_createCell: function(item, field) {
var $result;
- var fieldValue = item[field.name];
+ var fieldValue = this._getFieldValue(item, field.name, field);
if($.isFunction(field.cellRenderer)) {
$result = $(field.cellRenderer(fieldValue, item));
@@ -1096,10 +1107,12 @@
var $result = $("<tr>").addClass(this.editRowClass);
+ var self = this;
this._eachField(function(field) {
+ var fieldValue = self._getFieldValue(item, field.name, field);
$("<td>").addClass(field.editcss || field.css)
.appendTo($result)
- .append(field.editTemplate ? field.editTemplate(item[field.name], item) : "")
+ .append(field.editTemplate ? field.editTemplate(fieldValue, item) : "")
.width(field.width || "auto");
});
| 15 | Merge pull request #165 from ZainShaikh/master | 2 | .js | core | mit | tabalinas/jsgrid |
10062598 | <NME> jsgrid.core.js
<BEF> (function(window, $, undefined) {
var JSGRID = "JSGrid",
JSGRID_DATA_KEY = JSGRID,
JSGRID_ROW_DATA_KEY = "JSGridItem",
JSGRID_EDIT_ROW_DATA_KEY = "JSGridEditRow",
SORT_ORDER_ASC = "asc",
SORT_ORDER_DESC = "desc",
FIRST_PAGE_PLACEHOLDER = "{first}",
PAGES_PLACEHOLDER = "{pages}",
PREV_PAGE_PLACEHOLDER = "{prev}",
NEXT_PAGE_PLACEHOLDER = "{next}",
LAST_PAGE_PLACEHOLDER = "{last}",
PAGE_INDEX_PLACEHOLDER = "{pageIndex}",
PAGE_COUNT_PLACEHOLDER = "{pageCount}",
ITEM_COUNT_PLACEHOLDER = "{itemCount}",
EMPTY_HREF = "javascript:void(0);";
var getOrApply = function(value, context) {
if($.isFunction(value)) {
return value.apply(context, $.makeArray(arguments).slice(2));
}
return value;
};
var normalizePromise = function(promise) {
var d = $.Deferred();
if(promise && promise.then) {
promise.then(function() {
d.resolve.apply(d, arguments);
}, function() {
d.reject.apply(d, arguments);
});
} else {
d.resolve(promise);
}
return d.promise();
};
var defaultController = {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
};
function Grid(element, config) {
var $element = $(element);
$element.data(JSGRID_DATA_KEY, this);
this._container = $element;
this.data = [];
this.fields = [];
this._editingRow = null;
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._firstDisplayingPage = 1;
this._init(config);
this.render();
}
Grid.prototype = {
width: "auto",
height: "auto",
updateOnResize: true,
rowClass: $.noop,
rowRenderer: null,
rowClick: function(args) {
if(this.editing) {
this.editItem($(args.event.target).closest("tr"));
}
},
rowDoubleClick: $.noop,
noDataContent: "Not found",
noDataRowClass: "jsgrid-nodata-row",
heading: true,
headerRowRenderer: null,
headerRowClass: "jsgrid-header-row",
headerCellClass: "jsgrid-header-cell",
filtering: false,
filterRowRenderer: null,
filterRowClass: "jsgrid-filter-row",
inserting: false,
insertRowLocation: "bottom",
insertRowRenderer: null,
insertRowClass: "jsgrid-insert-row",
editing: false,
editRowRenderer: null,
editRowClass: "jsgrid-edit-row",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
selecting: true,
selectedRowClass: "jsgrid-selected-row",
oddRowClass: "jsgrid-row",
evenRowClass: "jsgrid-alt-row",
cellClass: "jsgrid-cell",
sorting: false,
sortableClass: "jsgrid-header-sortable",
sortAscClass: "jsgrid-header-sort jsgrid-header-sort-asc",
sortDescClass: "jsgrid-header-sort jsgrid-header-sort-desc",
paging: false,
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
pagerContainerClass: "jsgrid-pager-container",
pagerClass: "jsgrid-pager",
pagerNavButtonClass: "jsgrid-pager-nav-button",
pagerNavButtonInactiveClass: "jsgrid-pager-nav-inactive-button",
pageClass: "jsgrid-pager-page",
currentPageClass: "jsgrid-pager-current-page",
customLoading: false,
pageLoading: false,
autoload: false,
controller: defaultController,
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
invalidMessage: "Invalid data entered!",
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.message || null;
});
window.alert([this.invalidMessage].concat(messages).join("\n"));
},
onInit: $.noop,
onRefreshing: $.noop,
onRefreshed: $.noop,
onPageChanged: $.noop,
onItemDeleting: $.noop,
onItemDeleted: $.noop,
onItemInserting: $.noop,
onItemInserted: $.noop,
onItemEditing: $.noop,
onItemEditCancelling: $.noop,
onItemUpdating: $.noop,
onItemUpdated: $.noop,
onItemInvalid: $.noop,
onDataLoading: $.noop,
onDataLoaded: $.noop,
onDataExporting: $.noop,
onOptionChanging: $.noop,
onOptionChanged: $.noop,
onError: $.noop,
invalidClass: "jsgrid-invalid",
containerClass: "jsgrid",
tableClass: "jsgrid-table",
gridHeaderClass: "jsgrid-grid-header",
gridBodyClass: "jsgrid-grid-body",
_init: function(config) {
$.extend(this, config);
this._initLoadStrategy();
this._initController();
this._initFields();
this._attachWindowLoadResize();
this._attachWindowResizeCallback();
this._callEventHandler(this.onInit)
},
loadStrategy: function() {
return this.pageLoading
? new jsGrid.loadStrategies.PageLoadingStrategy(this)
: new jsGrid.loadStrategies.DirectLoadingStrategy(this);
},
_initLoadStrategy: function() {
this._loadStrategy = getOrApply(this.loadStrategy, this);
},
_initController: function() {
this._controller = $.extend({}, defaultController, getOrApply(this.controller, this));
},
renderTemplate: function(source, context, config) {
var args = [];
for(var key in config) {
args.push(config[key]);
}
args.unshift(source, context);
source = getOrApply.apply(null, args);
return (source === undefined || source === null) ? "" : source;
},
loadIndicator: function(config) {
return new jsGrid.LoadIndicator(config);
},
validation: function(config) {
return jsGrid.Validation && new jsGrid.Validation(config);
},
_initFields: function() {
var self = this;
self.fields = $.map(self.fields, function(field) {
if($.isPlainObject(field)) {
var fieldConstructor = (field.type && jsGrid.fields[field.type]) || jsGrid.Field;
field = new fieldConstructor(field);
}
field._grid = self;
return field;
});
},
_attachWindowLoadResize: function() {
$(window).on("load", $.proxy(this._refreshSize, this));
},
_attachWindowResizeCallback: function() {
if(this.updateOnResize) {
$(window).on("resize", $.proxy(this._refreshSize, this));
}
},
_detachWindowResizeCallback: function() {
$(window).off("resize", this._refreshSize);
},
option: function(key, value) {
var optionChangingEventArgs,
optionChangedEventArgs;
if(arguments.length === 1)
return this[key];
optionChangingEventArgs = {
option: key,
oldValue: this[key],
newValue: value
};
this._callEventHandler(this.onOptionChanging, optionChangingEventArgs);
this._handleOptionChange(optionChangingEventArgs.option, optionChangingEventArgs.newValue);
optionChangedEventArgs = {
option: optionChangingEventArgs.option,
value: optionChangingEventArgs.newValue
};
this._callEventHandler(this.onOptionChanged, optionChangedEventArgs);
},
fieldOption: function(field, key, value) {
field = this._normalizeField(field);
if(arguments.length === 2)
return field[key];
field[key] = value;
this._renderGrid();
},
_handleOptionChange: function(name, value) {
this[name] = value;
switch(name) {
case "width":
case "height":
this._refreshSize();
break;
case "rowClass":
case "rowRenderer":
case "rowClick":
case "rowDoubleClick":
case "noDataRowClass":
case "noDataContent":
case "selecting":
case "selectedRowClass":
case "oddRowClass":
case "evenRowClass":
this._refreshContent();
break;
case "pageButtonCount":
case "pagerFormat":
case "pagePrevText":
case "pageNextText":
case "pageFirstText":
case "pageLastText":
case "pageNavigatorNextText":
case "pageNavigatorPrevText":
case "pagerClass":
case "pagerNavButtonClass":
case "pageClass":
case "currentPageClass":
case "pagerRenderer":
this._refreshPager();
break;
case "fields":
this._initFields();
this.render();
break;
case "data":
case "editing":
case "heading":
case "filtering":
case "inserting":
case "paging":
this.refresh();
break;
case "loadStrategy":
case "pageLoading":
this._initLoadStrategy();
this.search();
break;
case "pageIndex":
this.openPage(value);
break;
case "pageSize":
this.refresh();
this.search();
break;
case "editRowRenderer":
case "editRowClass":
this.cancelEdit();
break;
case "updateOnResize":
this._detachWindowResizeCallback();
this._attachWindowResizeCallback();
break;
case "invalidNotify":
case "invalidMessage":
break;
default:
this.render();
break;
}
},
destroy: function() {
this._detachWindowResizeCallback();
this._clear();
this._container.removeData(JSGRID_DATA_KEY);
},
render: function() {
this._renderGrid();
return this.autoload ? this.loadData() : $.Deferred().resolve().promise();
},
_renderGrid: function() {
this._clear();
this._container.addClass(this.containerClass)
.css("position", "relative")
.append(this._createHeader())
.append(this._createBody());
this._pagerContainer = this._createPagerContainer();
this._loadIndicator = this._createLoadIndicator();
this._validation = this._createValidation();
this.refresh();
},
_createLoadIndicator: function() {
return getOrApply(this.loadIndicator, this, {
message: this.loadMessage,
shading: this.loadShading,
container: this._container
});
},
_createValidation: function() {
return getOrApply(this.validation, this);
},
_clear: function() {
this.cancelEdit();
clearTimeout(this._loadingTimer);
this._pagerContainer && this._pagerContainer.empty();
this._container.empty()
.css({ position: "", width: "", height: "" });
},
_createHeader: function() {
var $headerRow = this._headerRow = this._createHeaderRow(),
$filterRow = this._filterRow = this._createFilterRow(),
$insertRow = this._insertRow = this._createInsertRow();
var $headerGrid = this._headerGrid = $("<table>").addClass(this.tableClass)
.append($headerRow)
.append($filterRow)
.append($insertRow);
var $header = this._header = $("<div>").addClass(this.gridHeaderClass)
.addClass(this._scrollBarWidth() ? "jsgrid-header-scrollbar" : "")
.append($headerGrid);
return $header;
},
_createBody: function() {
var $content = this._content = $("<tbody>");
var $bodyGrid = this._bodyGrid = $("<table>").addClass(this.tableClass)
.append($content);
var $body = this._body = $("<div>").addClass(this.gridBodyClass)
.append($bodyGrid)
.on("scroll", $.proxy(function(e) {
this._header.scrollLeft(e.target.scrollLeft);
}, this));
return $body;
},
_createPagerContainer: function() {
var pagerContainer = this.pagerContainer || $("<div>").appendTo(this._container);
return $(pagerContainer).addClass(this.pagerContainerClass);
},
_eachField: function(callBack) {
var self = this;
$.each(this.fields, function(index, field) {
if(field.visible) {
callBack.call(self, field, index);
}
});
},
_createHeaderRow: function() {
if($.isFunction(this.headerRowRenderer))
return $(this.renderTemplate(this.headerRowRenderer, this));
var $result = $("<tr>").addClass(this.headerRowClass);
this._eachField(function(field, index) {
var $th = this._prepareCell("<th>", field, "headercss", this.headerCellClass)
.append(this.renderTemplate(field.headerTemplate, field))
.appendTo($result);
if(this.sorting && field.sorting) {
$th.addClass(this.sortableClass)
.on("click", $.proxy(function() {
this.sort(index);
}, this));
}
});
return $result;
},
_prepareCell: function(cell, field, cssprop, cellClass) {
return $(cell).css("width", field.width)
.addClass(cellClass || this.cellClass)
.addClass((cssprop && field[cssprop]) || field.css)
.addClass(field.align ? ("jsgrid-align-" + field.align) : "");
},
_createFilterRow: function() {
if($.isFunction(this.filterRowRenderer))
return $(this.renderTemplate(this.filterRowRenderer, this));
var $result = $("<tr>").addClass(this.filterRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "filtercss")
.append(this.renderTemplate(field.filterTemplate, field))
.appendTo($result);
});
return $result;
},
_createInsertRow: function() {
if($.isFunction(this.insertRowRenderer))
return $(this.renderTemplate(this.insertRowRenderer, this));
var $result = $("<tr>").addClass(this.insertRowClass);
this._eachField(function(field) {
this._prepareCell("<td>", field, "insertcss")
.append(this.renderTemplate(field.insertTemplate, field))
.appendTo($result);
});
return $result;
},
_callEventHandler: function(handler, eventParams) {
handler.call(this, $.extend(eventParams, {
grid: this
}));
return eventParams;
},
reset: function() {
this._resetSorting();
this._resetPager();
return this._loadStrategy.reset();
},
_resetPager: function() {
this._firstDisplayingPage = 1;
this._setPage(1);
},
_resetSorting: function() {
this._sortField = null;
this._sortOrder = SORT_ORDER_ASC;
this._clearSortingCss();
},
refresh: function() {
this._callEventHandler(this.onRefreshing);
this.cancelEdit();
this._refreshHeading();
this._refreshFiltering();
this._refreshInserting();
this._refreshContent();
this._refreshPager();
this._refreshSize();
this._callEventHandler(this.onRefreshed);
},
_refreshHeading: function() {
this._headerRow.toggle(this.heading);
},
_refreshFiltering: function() {
this._filterRow.toggle(this.filtering);
},
_refreshInserting: function() {
this._insertRow.toggle(this.inserting);
},
_refreshContent: function() {
var $content = this._content;
$content.empty();
if(!this.data.length) {
$content.append(this._createNoDataRow());
return this;
}
var indexFrom = this._loadStrategy.firstDisplayIndex();
var indexTo = this._loadStrategy.lastDisplayIndex();
for(var itemIndex = indexFrom; itemIndex < indexTo; itemIndex++) {
var item = this.data[itemIndex];
$content.append(this._createRow(item, itemIndex));
}
},
_createNoDataRow: function() {
var amountOfFields = 0;
this._eachField(function() {
amountOfFields++;
});
return $("<tr>").addClass(this.noDataRowClass)
.append($("<td>").addClass(this.cellClass).attr("colspan", amountOfFields)
.append(this.renderTemplate(this.noDataContent, this)));
},
_createRow: function(item, itemIndex) {
var $result;
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = item[field.name];
if($.isFunction(field.cellRenderer)) {
$result = $(field.cellRenderer(fieldValue, item));
event: e
});
}, this));
if(this.selecting) {
this._attachRowHover($result);
}
return $result;
},
_getRowClasses: function(item, itemIndex) {
var classes = [];
classes.push(((itemIndex + 1) % 2) ? this.oddRowClass : this.evenRowClass);
classes.push(getOrApply(this.rowClass, this, item, itemIndex));
return classes.join(" ");
},
_attachRowHover: function($row) {
var selectedRowClass = this.selectedRowClass;
$row.hover(function() {
$(this).addClass(selectedRowClass);
},
function() {
$(this).removeClass(selectedRowClass);
}
);
},
_renderCells: function($row, item) {
this._eachField(function(field) {
$row.append(this._createCell(item, field));
});
return this;
},
_createCell: function(item, field) {
var $result;
var fieldValue = this._getItemFieldValue(item, field);
var args = { value: fieldValue, item : item };
if($.isFunction(field.cellRenderer)) {
$result = this.renderTemplate(field.cellRenderer, field, args);
} else {
$result = $("<td>").append(this.renderTemplate(field.itemTemplate || fieldValue, field, args));
}
return this._prepareCell($result, field);
},
_getItemFieldValue: function(item, field) {
var props = field.name.split('.');
var result = item[props.shift()];
while(result && props.length) {
result = result[props.shift()];
}
return result;
},
_setItemFieldValue: function(item, field, value) {
var props = field.name.split('.');
var current = item;
var prop = props[0];
while(current && props.length) {
item = current;
prop = props.shift();
current = item[prop];
}
if(!current) {
while(props.length) {
item = item[prop] = {};
prop = props.shift();
}
}
item[prop] = value;
},
sort: function(field, order) {
if($.isPlainObject(field)) {
order = field.order;
field = field.field;
}
this._clearSortingCss();
this._setSortingParams(field, order);
this._setSortingCss();
return this._loadStrategy.sort();
},
_clearSortingCss: function() {
this._headerRow.find("th")
.removeClass(this.sortAscClass)
.removeClass(this.sortDescClass);
},
_setSortingParams: function(field, order) {
field = this._normalizeField(field);
order = order || ((this._sortField === field) ? this._reversedSortOrder(this._sortOrder) : SORT_ORDER_ASC);
this._sortField = field;
this._sortOrder = order;
},
_normalizeField: function(field) {
if($.isNumeric(field)) {
return this.fields[field];
}
if(typeof field === "string") {
return $.grep(this.fields, function(f) {
return f.name === field;
})[0];
}
return field;
},
_reversedSortOrder: function(order) {
return (order === SORT_ORDER_ASC ? SORT_ORDER_DESC : SORT_ORDER_ASC);
},
_setSortingCss: function() {
var fieldIndex = this._visibleFieldIndex(this._sortField);
this._headerRow.find("th").eq(fieldIndex)
.addClass(this._sortOrder === SORT_ORDER_ASC ? this.sortAscClass : this.sortDescClass);
},
_visibleFieldIndex: function(field) {
return $.inArray(field, $.grep(this.fields, function(f) { return f.visible; }));
},
_sortData: function() {
var sortFactor = this._sortFactor(),
sortField = this._sortField;
if(sortField) {
var self = this;
self.data.sort(function(item1, item2) {
var value1 = self._getItemFieldValue(item1, sortField);
var value2 = self._getItemFieldValue(item2, sortField);
return sortFactor * sortField.sortingFunc(value1, value2);
});
}
},
_sortFactor: function() {
return this._sortOrder === SORT_ORDER_ASC ? 1 : -1;
},
_itemsCount: function() {
return this._loadStrategy.itemsCount();
},
_pagesCount: function() {
var itemsCount = this._itemsCount(),
pageSize = this.pageSize;
return Math.floor(itemsCount / pageSize) + (itemsCount % pageSize ? 1 : 0);
},
_refreshPager: function() {
var $pagerContainer = this._pagerContainer;
$pagerContainer.empty();
if(this.paging) {
$pagerContainer.append(this._createPager());
}
var showPager = this.paging && this._pagesCount() > 1;
$pagerContainer.toggle(showPager);
},
_createPager: function() {
var $result;
if($.isFunction(this.pagerRenderer)) {
$result = $(this.pagerRenderer({
pageIndex: this.pageIndex,
pageCount: this._pagesCount()
}));
} else {
$result = $("<div>").append(this._createPagerByFormat());
}
$result.addClass(this.pagerClass);
return $result;
},
_createPagerByFormat: function() {
var pageIndex = this.pageIndex,
pageCount = this._pagesCount(),
itemCount = this._itemsCount(),
pagerParts = this.pagerFormat.split(" ");
return $.map(pagerParts, $.proxy(function(pagerPart) {
var result = pagerPart;
if(pagerPart === PAGES_PLACEHOLDER) {
result = this._createPages();
} else if(pagerPart === FIRST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageFirstText, 1, pageIndex > 1);
} else if(pagerPart === PREV_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pagePrevText, pageIndex - 1, pageIndex > 1);
} else if(pagerPart === NEXT_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageNextText, pageIndex + 1, pageIndex < pageCount);
} else if(pagerPart === LAST_PAGE_PLACEHOLDER) {
result = this._createPagerNavButton(this.pageLastText, pageCount, pageIndex < pageCount);
} else if(pagerPart === PAGE_INDEX_PLACEHOLDER) {
result = pageIndex;
} else if(pagerPart === PAGE_COUNT_PLACEHOLDER) {
result = pageCount;
} else if(pagerPart === ITEM_COUNT_PLACEHOLDER) {
result = itemCount;
}
return $.isArray(result) ? result.concat([" "]) : [result, " "];
}, this));
},
_createPages: function() {
var pageCount = this._pagesCount(),
pageButtonCount = this.pageButtonCount,
firstDisplayingPage = this._firstDisplayingPage,
pages = [];
if(firstDisplayingPage > 1) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorPrevText, this.showPrevPages));
}
for(var i = 0, pageNumber = firstDisplayingPage; i < pageButtonCount && pageNumber <= pageCount; i++, pageNumber++) {
pages.push(pageNumber === this.pageIndex
? this._createPagerCurrentPage()
: this._createPagerPage(pageNumber));
}
if((firstDisplayingPage + pageButtonCount - 1) < pageCount) {
pages.push(this._createPagerPageNavButton(this.pageNavigatorNextText, this.showNextPages));
}
return pages;
},
_createPagerNavButton: function(text, pageIndex, isActive) {
return this._createPagerButton(text, this.pagerNavButtonClass + (isActive ? "" : " " + this.pagerNavButtonInactiveClass),
isActive ? function() { this.openPage(pageIndex); } : $.noop);
},
_createPagerPageNavButton: function(text, handler) {
return this._createPagerButton(text, this.pagerNavButtonClass, handler);
},
_createPagerPage: function(pageIndex) {
return this._createPagerButton(pageIndex, this.pageClass, function() {
this.openPage(pageIndex);
});
},
_createPagerButton: function(text, css, handler) {
var $link = $("<a>").attr("href", EMPTY_HREF)
.html(text)
.on("click", $.proxy(handler, this));
return $("<span>").addClass(css).append($link);
},
_createPagerCurrentPage: function() {
return $("<span>")
.addClass(this.pageClass)
.addClass(this.currentPageClass)
.text(this.pageIndex);
},
_refreshSize: function() {
this._refreshHeight();
this._refreshWidth();
},
_refreshWidth: function() {
var width = (this.width === "auto") ? this._getAutoWidth() : this.width;
this._container.width(width);
},
_getAutoWidth: function() {
var $headerGrid = this._headerGrid,
$header = this._header;
$headerGrid.width("auto");
var contentWidth = $headerGrid.outerWidth();
var borderWidth = $header.outerWidth() - $header.innerWidth();
$headerGrid.width("");
return contentWidth + borderWidth;
},
_scrollBarWidth: (function() {
var result;
return function() {
if(result === undefined) {
var $ghostContainer = $("<div style='width:50px;height:50px;overflow:hidden;position:absolute;top:-10000px;left:-10000px;'></div>");
var $ghostContent = $("<div style='height:100px;'></div>");
$ghostContainer.append($ghostContent).appendTo("body");
var width = $ghostContent.innerWidth();
$ghostContainer.css("overflow-y", "auto");
var widthExcludingScrollBar = $ghostContent.innerWidth();
$ghostContainer.remove();
result = width - widthExcludingScrollBar;
}
return result;
};
})(),
_refreshHeight: function() {
var container = this._container,
pagerContainer = this._pagerContainer,
height = this.height,
nonBodyHeight;
container.height(height);
if(height !== "auto") {
height = container.height();
nonBodyHeight = this._header.outerHeight(true);
if(pagerContainer.parents(container).length) {
nonBodyHeight += pagerContainer.outerHeight(true);
}
this._body.outerHeight(height - nonBodyHeight);
}
},
showPrevPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this._firstDisplayingPage = (firstDisplayingPage > pageButtonCount) ? firstDisplayingPage - pageButtonCount : 1;
this._refreshPager();
},
showNextPages: function() {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount,
pageCount = this._pagesCount();
this._firstDisplayingPage = (firstDisplayingPage + 2 * pageButtonCount > pageCount)
? pageCount - pageButtonCount + 1
: firstDisplayingPage + pageButtonCount;
this._refreshPager();
},
openPage: function(pageIndex) {
if(pageIndex < 1 || pageIndex > this._pagesCount())
return;
this._setPage(pageIndex);
this._loadStrategy.openPage(pageIndex);
},
_setPage: function(pageIndex) {
var firstDisplayingPage = this._firstDisplayingPage,
pageButtonCount = this.pageButtonCount;
this.pageIndex = pageIndex;
if(pageIndex < firstDisplayingPage) {
this._firstDisplayingPage = pageIndex;
}
if(pageIndex > firstDisplayingPage + pageButtonCount - 1) {
this._firstDisplayingPage = pageIndex - pageButtonCount + 1;
}
this._callEventHandler(this.onPageChanged, {
pageIndex: pageIndex
});
},
_controllerCall: function(method, param, isCanceled, doneCallback) {
if(isCanceled)
return $.Deferred().reject().promise();
this._showLoading();
var controller = this._controller;
if(!controller || !controller[method]) {
throw Error("controller has no method '" + method + "'");
}
return normalizePromise(controller[method](param))
.done($.proxy(doneCallback, this))
.fail($.proxy(this._errorHandler, this))
.always($.proxy(this._hideLoading, this));
},
_errorHandler: function() {
this._callEventHandler(this.onError, {
args: $.makeArray(arguments)
});
},
_showLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadingTimer = setTimeout($.proxy(function() {
this._loadIndicator.show();
}, this), this.loadIndicationDelay);
},
_hideLoading: function() {
if(!this.loadIndication)
return;
clearTimeout(this._loadingTimer);
this._loadIndicator.hide();
},
search: function(filter) {
this._resetSorting();
this._resetPager();
return this.loadData(filter);
},
loadData: function(filter) {
filter = filter || (this.filtering ? this.getFilter() : {});
$.extend(filter, this._loadStrategy.loadParams(), this._sortingParams());
var args = this._callEventHandler(this.onDataLoading, {
filter: filter
});
return this._controllerCall("loadData", filter, args.cancel, function(loadedData) {
if(!loadedData)
return;
this._loadStrategy.finishLoad(loadedData);
this._callEventHandler(this.onDataLoaded, {
data: loadedData
});
});
},
exportData: function(exportOptions){
var options = exportOptions || {};
var type = options.type || "csv";
var result = "";
this._callEventHandler(this.onDataExporting);
switch(type){
case "csv":
result = this._dataToCsv(options);
break;
}
return result;
},
_dataToCsv: function(options){
var options = options || {};
var includeHeaders = options.hasOwnProperty("includeHeaders") ? options.includeHeaders : true;
var subset = options.subset || "all";
var filter = options.filter || undefined;
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
$("<td>").addClass(field.editcss || field.css)
.appendTo($result)
.append(field.editTemplate ? field.editTemplate(item[field.name], item) : "")
.width(field.width || "auto");
});
fieldNames[i] = field.title || field.name;
}
}
var headerLine = this._itemToCsv(fieldNames,{},options);
result.push(headerLine);
}
var exportStartIndex = 0;
var exportEndIndex = this.data.length;
switch(subset){
case "visible":
exportEndIndex = this._firstDisplayingPage * this.pageSize;
exportStartIndex = exportEndIndex - this.pageSize;
case "all":
default:
break;
}
for (var i = exportStartIndex; i < exportEndIndex; i++){
var item = this.data[i];
var itemLine = "";
var includeItem = true;
if (filter)
if (!filter(item))
includeItem = false;
if (includeItem){
itemLine = this._itemToCsv(item, this.fields, options);
result.push(itemLine);
}
}
return result.join("");
},
_itemToCsv: function(item, fields, options){
var options = options || {};
var delimiter = options.delimiter || "|";
var encapsulate = options.hasOwnProperty("encapsulate") ? options.encapsulate : true;
var newline = options.newline || "\r\n";
var transforms = options.transforms || {};
var fields = fields || {};
var getItem = this._getItemFieldValue;
var result = [];
Object.keys(item).forEach(function(key,index) {
var entry = "";
//Fields.length is greater than 0 when we are matching agaisnt fields
//Field.length will be 0 when exporting header rows
if (fields.length > 0){
var field = fields[index];
//Field may be excluded from data export
if ("includeInDataExport" in field){
if (field.includeInDataExport){
//Field may be a select, which requires additional logic
if (field.type === "select"){
var selectedItem = getItem(item, field);
var resultItem = $.grep(field.items, function(item, index) {
return item[field.valueField] === selectedItem;
})[0] || "";
entry = resultItem[field.textField];
}
else{
entry = getItem(item, field);
}
}
else{
return;
}
}
else{
entry = getItem(item, field);
}
if (transforms.hasOwnProperty(field.name)){
entry = transforms[field.name](entry);
}
}
else{
entry = item[key];
}
if (encapsulate){
entry = '"'+entry+'"';
}
result.push(entry);
});
return result.join(delimiter) + newline;
},
getFilter: function() {
var result = {};
this._eachField(function(field) {
if(field.filtering) {
this._setItemFieldValue(result, field, field.filterValue());
}
});
return result;
},
_sortingParams: function() {
if(this.sorting && this._sortField) {
return {
sortField: this._sortField.name,
sortOrder: this._sortOrder
};
}
return {};
},
getSorting: function() {
var sortingParams = this._sortingParams();
return {
field: sortingParams.sortField,
order: sortingParams.sortOrder
};
},
clearFilter: function() {
var $filterRow = this._createFilterRow();
this._filterRow.replaceWith($filterRow);
this._filterRow = $filterRow;
return this.search();
},
insertItem: function(item) {
var insertingItem = item || this._getValidatedInsertItem();
if(!insertingItem)
return $.Deferred().reject().promise();
var args = this._callEventHandler(this.onItemInserting, {
item: insertingItem
});
return this._controllerCall("insertItem", insertingItem, args.cancel, function(insertedItem) {
insertedItem = insertedItem || insertingItem;
this._loadStrategy.finishInsert(insertedItem, this.insertRowLocation);
this._callEventHandler(this.onItemInserted, {
item: insertedItem
});
});
},
_getValidatedInsertItem: function() {
var item = this._getInsertItem();
return this._validateItem(item, this._insertRow) ? item : null;
},
_getInsertItem: function() {
var result = {};
this._eachField(function(field) {
if(field.inserting) {
this._setItemFieldValue(result, field, field.insertValue());
}
});
return result;
},
_validateItem: function(item, $row) {
var validationErrors = [];
var args = {
item: item,
itemIndex: this._rowIndex($row),
row: $row
};
this._eachField(function(field) {
if(!field.validate ||
($row === this._insertRow && !field.inserting) ||
($row === this._getEditRow() && !field.editing))
return;
var fieldValue = this._getItemFieldValue(item, field);
var errors = this._validation.validate($.extend({
value: fieldValue,
rules: field.validate
}, args));
this._setCellValidity($row.children().eq(this._visibleFieldIndex(field)), errors);
if(!errors.length)
return;
validationErrors.push.apply(validationErrors,
$.map(errors, function(message) {
return { field: field, message: message };
}));
});
if(!validationErrors.length)
return true;
var invalidArgs = $.extend({
errors: validationErrors
}, args);
this._callEventHandler(this.onItemInvalid, invalidArgs);
this.invalidNotify(invalidArgs);
return false;
},
_setCellValidity: function($cell, errors) {
$cell
.toggleClass(this.invalidClass, !!errors.length)
.attr("title", errors.join("\n"));
},
clearInsert: function() {
var insertRow = this._createInsertRow();
this._insertRow.replaceWith(insertRow);
this._insertRow = insertRow;
this.refresh();
},
editItem: function(item) {
var $row = this.rowByItem(item);
if($row.length) {
this._editRow($row);
}
},
rowByItem: function(item) {
if(item.jquery || item.nodeType)
return $(item);
return this._content.find("tr").filter(function() {
return $.data(this, JSGRID_ROW_DATA_KEY) === item;
});
},
_editRow: function($row) {
if(!this.editing)
return;
var item = $row.data(JSGRID_ROW_DATA_KEY);
var args = this._callEventHandler(this.onItemEditing, {
row: $row,
item: item,
itemIndex: this._itemIndex(item)
});
if(args.cancel)
return;
if(this._editingRow) {
this.cancelEdit();
}
var $editRow = this._createEditRow(item);
this._editingRow = $row;
$row.hide();
$editRow.insertBefore($row);
$row.data(JSGRID_EDIT_ROW_DATA_KEY, $editRow);
},
_createEditRow: function(item) {
if($.isFunction(this.editRowRenderer)) {
return $(this.renderTemplate(this.editRowRenderer, this, { item: item, itemIndex: this._itemIndex(item) }));
}
var $result = $("<tr>").addClass(this.editRowClass);
this._eachField(function(field) {
var fieldValue = this._getItemFieldValue(item, field);
this._prepareCell("<td>", field, "editcss")
.append(this.renderTemplate(field.editTemplate || "", field, { value: fieldValue, item: item }))
.appendTo($result);
});
return $result;
},
updateItem: function(item, editedItem) {
if(arguments.length === 1) {
editedItem = item;
}
var $row = item ? this.rowByItem(item) : this._editingRow;
editedItem = editedItem || this._getValidatedEditedItem();
if(!editedItem)
return;
return this._updateRow($row, editedItem);
},
_getValidatedEditedItem: function() {
var item = this._getEditedItem();
return this._validateItem(item, this._getEditRow()) ? item : null;
},
_updateRow: function($updatingRow, editedItem) {
var updatingItem = $updatingRow.data(JSGRID_ROW_DATA_KEY),
updatingItemIndex = this._itemIndex(updatingItem),
updatedItem = $.extend(true, {}, updatingItem, editedItem);
var args = this._callEventHandler(this.onItemUpdating, {
row: $updatingRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: updatingItem
});
return this._controllerCall("updateItem", updatedItem, args.cancel, function(loadedUpdatedItem) {
var previousItem = $.extend(true, {}, updatingItem);
updatedItem = loadedUpdatedItem || $.extend(true, updatingItem, editedItem);
var $updatedRow = this._finishUpdate($updatingRow, updatedItem, updatingItemIndex);
this._callEventHandler(this.onItemUpdated, {
row: $updatedRow,
item: updatedItem,
itemIndex: updatingItemIndex,
previousItem: previousItem
});
});
},
_rowIndex: function(row) {
return this._content.children().index($(row));
},
_itemIndex: function(item) {
return $.inArray(item, this.data);
},
_finishUpdate: function($updatingRow, updatedItem, updatedItemIndex) {
this.cancelEdit();
this.data[updatedItemIndex] = updatedItem;
var $updatedRow = this._createRow(updatedItem, updatedItemIndex);
$updatingRow.replaceWith($updatedRow);
return $updatedRow;
},
_getEditedItem: function() {
var result = {};
this._eachField(function(field) {
if(field.editing) {
this._setItemFieldValue(result, field, field.editValue());
}
});
return result;
},
cancelEdit: function() {
if(!this._editingRow)
return;
var $row = this._editingRow,
editingItem = $row.data(JSGRID_ROW_DATA_KEY),
editingItemIndex = this._itemIndex(editingItem);
this._callEventHandler(this.onItemEditCancelling, {
row: $row,
item: editingItem,
itemIndex: editingItemIndex
});
this._getEditRow().remove();
this._editingRow.show();
this._editingRow = null;
},
_getEditRow: function() {
return this._editingRow && this._editingRow.data(JSGRID_EDIT_ROW_DATA_KEY);
},
deleteItem: function(item) {
var $row = this.rowByItem(item);
if(!$row.length)
return;
if(this.confirmDeleting && !window.confirm(getOrApply(this.deleteConfirm, this, $row.data(JSGRID_ROW_DATA_KEY))))
return;
return this._deleteRow($row);
},
_deleteRow: function($row) {
var deletingItem = $row.data(JSGRID_ROW_DATA_KEY),
deletingItemIndex = this._itemIndex(deletingItem);
var args = this._callEventHandler(this.onItemDeleting, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
return this._controllerCall("deleteItem", deletingItem, args.cancel, function() {
this._loadStrategy.finishDelete(deletingItem, deletingItemIndex);
this._callEventHandler(this.onItemDeleted, {
row: $row,
item: deletingItem,
itemIndex: deletingItemIndex
});
});
}
};
$.fn.jsGrid = function(config) {
var args = $.makeArray(arguments),
methodArgs = args.slice(1),
result = this;
this.each(function() {
var $element = $(this),
instance = $element.data(JSGRID_DATA_KEY),
methodResult;
if(instance) {
if(typeof config === "string") {
methodResult = instance[config].apply(instance, methodArgs);
if(methodResult !== undefined && methodResult !== instance) {
result = methodResult;
return false;
}
} else {
instance._detachWindowResizeCallback();
instance._init(config);
instance.render();
}
} else {
new Grid($element, config);
}
});
return result;
};
var fields = {};
var setDefaults = function(config) {
var componentPrototype;
if($.isPlainObject(config)) {
componentPrototype = Grid.prototype;
} else {
componentPrototype = fields[config].prototype;
config = arguments[1] || {};
}
$.extend(componentPrototype, config);
};
var locales = {};
var locale = function(lang) {
var localeConfig = $.isPlainObject(lang) ? lang : locales[lang];
if(!localeConfig)
throw Error("unknown locale " + lang);
setLocale(jsGrid, localeConfig);
};
var setLocale = function(obj, localeConfig) {
$.each(localeConfig, function(field, value) {
if($.isPlainObject(value)) {
setLocale(obj[field] || obj[field[0].toUpperCase() + field.slice(1)], value);
return;
}
if(obj.hasOwnProperty(field)) {
obj[field] = value;
} else {
obj.prototype[field] = value;
}
});
};
window.jsGrid = {
Grid: Grid,
fields: fields,
setDefaults: setDefaults,
locales: locales,
locale: locale,
version: "@VERSION"
};
}(window, jQuery));
<MSG> Merge pull request #165 from ZainShaikh/master
Core: Support dot notation for properties binding
<DFF> @@ -606,9 +606,20 @@
return this;
},
+ _getFieldValue: function(item, name, field) {
+ var props = name.split('.');
+ var fieldValue = item[props.shift()];
+
+ while (props.length > 0) {
+ fieldValue = fieldValue[props.shift()];
+ }
+
+ return fieldValue;
+ },
+
_createCell: function(item, field) {
var $result;
- var fieldValue = item[field.name];
+ var fieldValue = this._getFieldValue(item, field.name, field);
if($.isFunction(field.cellRenderer)) {
$result = $(field.cellRenderer(fieldValue, item));
@@ -1096,10 +1107,12 @@
var $result = $("<tr>").addClass(this.editRowClass);
+ var self = this;
this._eachField(function(field) {
+ var fieldValue = self._getFieldValue(item, field.name, field);
$("<td>").addClass(field.editcss || field.css)
.appendTo($result)
- .append(field.editTemplate ? field.editTemplate(item[field.name], item) : "")
+ .append(field.editTemplate ? field.editTemplate(fieldValue, item) : "")
.width(field.width || "auto");
});
| 15 | Merge pull request #165 from ZainShaikh/master | 2 | .js | core | mit | tabalinas/jsgrid |
10062599 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062600 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062601 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062602 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062603 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062604 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062605 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062606 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062607 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062608 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062609 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062610 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062611 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062612 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062613 | <NME> TextArea.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.TextInput;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Indentation;
using AvaloniaEdit.Rendering;
using AvaloniaEdit.Search;
using AvaloniaEdit.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace AvaloniaEdit.Editing
{
/// <summary>
/// Control that wraps a TextView and adds support for user input and the caret.
/// </summary>
public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable
{
/// <summary>
/// This is the extra scrolling space that occurs after the last line.
/// </summary>
private const int AdditionalVerticalScrollAmount = 2;
private ILogicalScrollable _logicalScrollable;
private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient();
#region Constructor
static TextArea()
{
KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None);
FocusableProperty.OverrideDefaultValue<TextArea>(true);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
AffectsArrange<TextArea>(OffsetProperty);
AffectsRender<TextArea>(OffsetProperty);
TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) =>
{
if (!ta.IsReadOnly)
{
e.Client = ta._imClient;
}
});
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
public TextArea() : this(new TextView())
{
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel);
}
/// <summary>
/// Creates a new TextArea instance.
/// </summary>
protected TextArea(TextView textView)
{
TextView = textView ?? throw new ArgumentNullException(nameof(textView));
_logicalScrollable = textView;
Options = textView.Options;
_selection = EmptySelection = new EmptySelection(this);
textView.Services.AddService(this);
textView.LineTransformers.Add(new SelectionColorizer(this));
textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace);
Caret = new Caret(this);
Caret.PositionChanged += (sender, e) => RequestSelectionValidation();
Caret.PositionChanged += CaretPositionChanged;
AttachTypingEvents();
LeftMargins.CollectionChanged += LeftMargins_CollectionChanged;
DefaultInputHandler = new TextAreaDefaultInputHandler(this);
ActiveInputHandler = DefaultInputHandler;
// TODO
//textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ =>
//{
// TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight));
//});
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter)
{
contentPresenter.Content = TextView;
}
}
internal void AddChild(IVisual visual)
{
VisualChildren.Add(visual);
InvalidateArrange();
}
internal void RemoveChild(IVisual visual)
{
VisualChildren.Remove(visual);
}
#endregion
/// <summary>
/// Defines the <see cref="IScrollable.Offset" /> property.
/// </summary>
public static readonly DirectProperty<TextArea, Vector> OffsetProperty =
AvaloniaProperty.RegisterDirect<TextArea, Vector>(
nameof(IScrollable.Offset),
o => (o as IScrollable).Offset,
(o, v) => (o as IScrollable).Offset = v);
#region InputHandler management
/// <summary>
/// Gets the default input handler.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public TextAreaDefaultInputHandler DefaultInputHandler { get; }
private ITextAreaInputHandler _activeInputHandler;
private bool _isChangingInputHandler;
/// <summary>
/// Gets/Sets the active input handler.
/// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ITextAreaInputHandler ActiveInputHandler
{
get => _activeInputHandler;
set
{
if (value != null && value.TextArea != this)
throw new ArgumentException("The input handler was created for a different text area than this one.");
if (_isChangingInputHandler)
throw new InvalidOperationException("Cannot set ActiveInputHandler recursively");
if (_activeInputHandler != value)
{
_isChangingInputHandler = true;
try
{
// pop the whole stack
PopStackedInputHandler(StackedInputHandlers.LastOrDefault());
Debug.Assert(StackedInputHandlers.IsEmpty);
_activeInputHandler?.Detach();
_activeInputHandler = value;
value?.Attach();
}
finally
{
_isChangingInputHandler = false;
}
ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty);
}
}
}
/// <summary>
/// Occurs when the ActiveInputHandler property changes.
/// </summary>
public event EventHandler ActiveInputHandlerChanged;
/// <summary>
/// Gets the list of currently active stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty;
/// <summary>
/// Pushes an input handler onto the list of stacked input handlers.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (inputHandler == null)
throw new ArgumentNullException(nameof(inputHandler));
StackedInputHandlers = StackedInputHandlers.Push(inputHandler);
inputHandler.Attach();
}
/// <summary>
/// Pops the stacked input handler (and all input handlers above it).
/// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method
/// does nothing.
/// </summary>
/// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks>
public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler)
{
if (StackedInputHandlers.Any(i => i == inputHandler))
{
ITextAreaInputHandler oldHandler;
do
{
oldHandler = StackedInputHandlers.Peek();
StackedInputHandlers = StackedInputHandlers.Pop();
oldHandler.Detach();
} while (oldHandler != inputHandler);
}
}
#endregion
#region Document property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty
= TextView.DocumentProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
/// <inheritdoc/>
public event EventHandler DocumentChanged;
/// <summary>
/// Gets if the the document displayed by the text editor is readonly
/// </summary>
public bool IsReadOnly
{
get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance;
}
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished);
}
TextView.Document = newValue;
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging);
TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged);
TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted);
TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished);
InvalidateArrange();
}
// Reset caret location and selection: this is necessary because the caret/selection might be invalid
// in the new document (e.g. if new document is shorter than the old document).
Caret.Location = new TextLocation(1, 1);
ClearSelection();
DocumentChanged?.Invoke(this, EventArgs.Empty);
//CommandManager.InvalidateRequerySuggested();
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty
= TextView.OptionsProperty.AddOwner<TextArea>();
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
private void OnOptionChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged);
}
TextView.Options = newValue;
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region Caret handling on document changes
private void OnDocumentChanging(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanging();
}
private void OnDocumentChanged(object sender, DocumentChangeEventArgs e)
{
Caret.OnDocumentChanged(e);
Selection = _selection.UpdateOnDocumentChange(e);
}
private void OnUpdateStarted(object sender, EventArgs e)
{
Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this));
}
private void OnUpdateFinished(object sender, EventArgs e)
{
Caret.OnDocumentUpdateFinished();
}
private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation
{
// keep textarea in weak reference because the IUndoableOperation is stored with the document
private readonly WeakReference _textAreaReference;
private readonly TextViewPosition _caretPosition;
private readonly Selection _selection;
public RestoreCaretAndSelectionUndoAction(TextArea textArea)
{
_textAreaReference = new WeakReference(textArea);
// Just save the old caret position, no need to validate here.
// If we restore it, we'll validate it anyways.
_caretPosition = textArea.Caret.NonValidatedPosition;
_selection = textArea.Selection;
}
public void Undo()
{
var textArea = (TextArea)_textAreaReference.Target;
if (textArea != null)
{
textArea.Caret.Position = _caretPosition;
textArea.Selection = _selection;
}
}
public void Redo()
{
// redo=undo: we just restore the caret/selection state
Undo();
}
}
#endregion
#region TextView property
/// <summary>
/// Gets the text view used to display text in this text area.
/// </summary>
public TextView TextView { get; }
#endregion
#region Selection property
internal readonly Selection EmptySelection;
private Selection _selection;
/// <summary>
/// Occurs when the selection has changed.
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Gets/Sets the selection in this text area.
/// </summary>
public Selection Selection
{
get => _selection;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.TextArea != this)
throw new ArgumentException("Cannot use a Selection instance that belongs to another text area.");
if (!Equals(_selection, value))
{
if (TextView != null)
{
var oldSegment = _selection.SurroundingSegment;
var newSegment = value.SurroundingSegment;
if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null))
{
// perf optimization:
// When a simple selection changes, don't redraw the whole selection, but only the changed parts.
var oldSegmentOffset = oldSegment.Offset;
var newSegmentOffset = newSegment.Offset;
if (oldSegmentOffset != newSegmentOffset)
{
TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset),
Math.Abs(oldSegmentOffset - newSegmentOffset));
}
var oldSegmentEndOffset = oldSegment.EndOffset;
var newSegmentEndOffset = newSegment.EndOffset;
if (oldSegmentEndOffset != newSegmentEndOffset)
{
TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset),
Math.Abs(oldSegmentEndOffset - newSegmentEndOffset));
}
}
else
{
TextView.Redraw(oldSegment);
TextView.Redraw(newSegment);
}
}
_selection = value;
SelectionChanged?.Invoke(this, EventArgs.Empty);
// a selection change causes commands like copy/paste/etc. to change status
//CommandManager.InvalidateRequerySuggested();
}
}
}
/// <summary>
/// Clears the current selection.
/// </summary>
public void ClearSelection()
{
Selection = EmptySelection;
}
/// <summary>
/// The <see cref="SelectionBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionBrushProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush");
/// <summary>
/// Gets/Sets the background brush used for the selection.
/// </summary>
public IBrush SelectionBrush
{
get => GetValue(SelectionBrushProperty);
set => SetValue(SelectionBrushProperty, value);
}
/// <summary>
/// The <see cref="SelectionForeground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> SelectionForegroundProperty =
AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground");
/// <summary>
/// Gets/Sets the foreground brush used for selected text.
/// </summary>
public IBrush SelectionForeground
{
get => GetValue(SelectionForegroundProperty);
set => SetValue(SelectionForegroundProperty, value);
}
/// <summary>
/// The <see cref="SelectionBorder"/> property.
/// </summary>
public static readonly StyledProperty<Pen> SelectionBorderProperty =
AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder");
/// <summary>
/// Gets/Sets the pen used for the border of the selection.
/// </summary>
public Pen SelectionBorder
{
get => GetValue(SelectionBorderProperty);
set => SetValue(SelectionBorderProperty, value);
}
/// <summary>
/// The <see cref="SelectionCornerRadius"/> property.
/// </summary>
public static readonly StyledProperty<double> SelectionCornerRadiusProperty =
AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0);
/// <summary>
/// Gets/Sets the corner radius of the selection.
/// </summary>
public double SelectionCornerRadius
{
get => GetValue(SelectionCornerRadiusProperty);
set => SetValue(SelectionCornerRadiusProperty, value);
}
#endregion
#region Force caret to stay inside selection
private bool _ensureSelectionValidRequested;
private int _allowCaretOutsideSelection;
private void RequestSelectionValidation()
{
if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0)
{
_ensureSelectionValidRequested = true;
Dispatcher.UIThread.Post(EnsureSelectionValid);
}
}
/// <summary>
/// Code that updates only the caret but not the selection can cause confusion when
/// keys like 'Delete' delete the (possibly invisible) selected text and not the
/// text around the caret.
///
/// So we'll ensure that the caret is inside the selection.
/// (when the caret is not in the selection, we'll clear the selection)
///
/// This method is invoked using the Dispatcher so that code may temporarily violate this rule
/// (e.g. most 'extend selection' methods work by first setting the caret, then the selection),
/// it's sufficient to fix it after any event handlers have run.
/// </summary>
private void EnsureSelectionValid()
{
_ensureSelectionValidRequested = false;
if (_allowCaretOutsideSelection == 0)
{
if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset))
{
ClearSelection();
}
}
}
/// <summary>
/// Temporarily allows positioning the caret outside the selection.
/// Dispose the returned IDisposable to revert the allowance.
/// </summary>
/// <remarks>
/// The text area only forces the caret to be inside the selection when other events
/// have finished running (using the dispatcher), so you don't have to use this method
/// for temporarily positioning the caret in event handlers.
/// This method is only necessary if you want to run the dispatcher, e.g. if you
/// perform a drag'n'drop operation.
/// </remarks>
public IDisposable AllowCaretOutsideSelection()
{
VerifyAccess();
_allowCaretOutsideSelection++;
return new CallbackOnDispose(
delegate
{
VerifyAccess();
_allowCaretOutsideSelection--;
RequestSelectionValidation();
});
}
#endregion
#region Properties
/// <summary>
/// Gets the Caret used for this text area.
/// </summary>
public Caret Caret { get; }
/// <summary>
/// Scrolls the text view so that the requested line is in the middle.
/// If the textview can be scrolled.
/// </summary>
/// <param name="line">The line to scroll to.</param>
public void ScrollToLine (int line)
{
var viewPortLines = (int)(this as IScrollable).Viewport.Height;
if (viewPortLines < Document.LineCount)
{
ScrollToLine(line, 2, viewPortLines / 2);
}
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesEitherSide">The number of lines above and below.</param>
public void ScrollToLine(int line, int linesEitherSide)
{
ScrollToLine(line, linesEitherSide, linesEitherSide);
}
/// <summary>
/// Scrolls the textview to a position with n lines above and below it.
/// </summary>
/// <param name="line">the requested line number.</param>
/// <param name="linesAbove">The number of lines above.</param>
/// <param name="linesBelow">The number of lines below.</param>
public void ScrollToLine(int line, int linesAbove, int linesBelow)
{
var offset = line - linesAbove;
if (offset < 0)
{
offset = 0;
}
this.BringIntoView(new Rect(1, offset, 0, 1));
offset = line + linesBelow;
if (offset >= 0)
{
this.BringIntoView(new Rect(1, offset, 0, 1));
}
}
private void CaretPositionChanged(object sender, EventArgs e)
{
if (TextView == null)
return;
TextView.HighlightedLine = Caret.Line;
ScrollToLine(Caret.Line, 2);
Dispatcher.UIThread.InvokeAsync(() =>
{
(this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty);
});
}
public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty
= AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins),
c => c.LeftMargins);
/// <summary>
/// Gets the collection of margins displayed to the left of the text view.
/// </summary>
public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>();
private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (var c in e.OldItems.OfType<ITextViewConnect>())
{
c.RemoveFromTextView(TextView);
}
}
if (e.NewItems != null)
{
foreach (var c in e.NewItems.OfType<ITextViewConnect>())
{
c.AddToTextView(TextView);
}
}
}
private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance;
/// <summary>
/// Gets/Sets an object that provides read-only sections for the text area.
/// </summary>
public IReadOnlySectionProvider ReadOnlySectionProvider
{
get => _readOnlySectionProvider;
set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// The <see cref="RightClickMovesCaret"/> property.
/// </summary>
public static readonly StyledProperty<bool> RightClickMovesCaretProperty =
AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false);
/// <summary>
/// Determines whether caret position should be changed to the mouse position when you right click or not.
/// </summary>
public bool RightClickMovesCaret
{
get => GetValue(RightClickMovesCaretProperty);
set => SetValue(RightClickMovesCaretProperty, value);
}
#endregion
#region Focus Handling (Show/Hide Caret)
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
Focus();
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
Caret.Show();
_imClient.SetTextArea(this);
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
Caret.Hide();
_imClient.SetTextArea(null);
}
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
{
// TODO: check this
// ASCII 0x1b = ESC.
public event EventHandler<TextInputEventArgs> TextEntering;
/// <summary>
/// Occurs when the TextArea receives text input.
/// but occurs immediately after the TextArea handles the TextInput event.
/// </summary>
public event EventHandler<TextInputEventArgs> TextEntered;
/// <summary>
/// Raises the TextEntering event.
/// </summary>
protected virtual void OnTextEntering(TextInputEventArgs e)
{
TextEntering?.Invoke(this, e);
}
/// <summary>
/// Raises the TextEntered event.
/// </summary>
protected virtual void OnTextEntered(TextInputEventArgs e)
{
TextEntered?.Invoke(this, e);
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
// produces a TextInput event with that old ASCII control char
// when Escape is pressed. We'll just ignore it.
// A deadkey followed by backspace causes a textinput event for the BS character.
// Similarly, some shortcuts like Alt+Space produce an empty TextInput event.
// We have to ignore those (not handle them) to keep the shortcut working.
return;
}
HideMouseCursor();
PerformTextInput(e);
e.Handled = true;
}
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(string text)
{
var e = new TextInputEventArgs
{
Text = text,
RoutedEvent = TextInputEvent
};
PerformTextInput(e);
}
/// <summary>
/// Performs text input.
/// This raises the <see cref="TextEntering"/> event, replaces the selection with the text,
/// and then raises the <see cref="TextEntered"/> event.
/// </summary>
public void PerformTextInput(TextInputEventArgs e)
{
if (e == null)
throw new ArgumentNullException(nameof(e));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
OnTextEntering(e);
if (!e.Handled)
{
if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n")
ReplaceSelectionWithNewLine();
else
{
// TODO
//if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset)
// EditingCommands.SelectRightByCharacter.Execute(null, this);
ReplaceSelectionWithText(e.Text);
}
OnTextEntered(e);
Caret.BringCaretToView();
}
}
private void ReplaceSelectionWithNewLine()
{
var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line);
using (Document.RunUpdate())
{
ReplaceSelectionWithText(newLine);
if (IndentationStrategy != null)
{
var line = Document.GetLineByNumber(Caret.Line);
var deletable = GetDeletableSegments(line);
if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length)
{
// use indentation strategy only if the line is not read-only
IndentationStrategy.IndentLine(Document, line);
}
}
}
}
internal void RemoveSelectedText()
{
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(string.Empty);
#if DEBUG
if (!_selection.IsEmpty)
{
foreach (var s in _selection.Segments)
{
Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any());
}
}
#endif
}
internal void ReplaceSelectionWithText(string newText)
{
if (newText == null)
throw new ArgumentNullException(nameof(newText));
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
_selection.ReplaceSelectionWithText(newText);
}
internal ISegment[] GetDeletableSegments(ISegment segment)
{
var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment);
if (deletableSegments == null)
throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null");
var array = deletableSegments.ToArray();
var lastIndex = segment.Offset;
foreach (var t in array)
{
if (t.Offset < lastIndex)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
lastIndex = t.EndOffset;
}
if (lastIndex > segment.EndOffset)
throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)");
return array;
}
#endregion
#region IndentationStrategy property
/// <summary>
/// IndentationStrategy property.
/// </summary>
public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty =
AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy());
/// <summary>
/// Gets/Sets the indentation strategy used when inserting new lines.
/// </summary>
public IIndentationStrategy IndentationStrategy
{
get => GetValue(IndentationStrategyProperty);
set => SetValue(IndentationStrategyProperty, value);
}
#endregion
#region OnKeyDown/OnKeyUp
// Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys.
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyDown(e);
}
}
/// <inheritdoc/>
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
TextView.InvalidateCursorIfPointerWithinTextView();
}
private void OnPreviewKeyUp(object sender, KeyEventArgs e)
{
foreach (var h in StackedInputHandlers)
{
if (e.Handled)
break;
h.OnPreviewKeyUp(e);
}
}
#endregion
#region Hide Mouse Cursor While Typing
private bool _isMouseCursorHidden;
private void AttachTypingEvents()
{
// Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer)
PointerEntered += delegate { ShowMouseCursor(); };
PointerExited += delegate { ShowMouseCursor(); };
}
private void ShowMouseCursor()
{
if (_isMouseCursorHidden)
{
_isMouseCursorHidden = false;
}
}
private void HideMouseCursor()
{
if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver)
{
_isMouseCursorHidden = true;
}
}
#endregion
#region Overstrike mode
/// <summary>
/// The <see cref="OverstrikeMode"/> dependency property.
/// </summary>
public static readonly StyledProperty<bool> OverstrikeModeProperty =
AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode");
/// <summary>
/// Gets/Sets whether overstrike mode is active.
/// </summary>
public bool OverstrikeMode
{
get => GetValue(OverstrikeModeProperty);
set => SetValue(OverstrikeModeProperty, value);
}
#endregion
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == SelectionBrushProperty
|| change.Property == SelectionBorderProperty
|| change.Property == SelectionForegroundProperty
|| change.Property == SelectionCornerRadiusProperty)
{
TextView.Redraw();
}
else if (change.Property == OverstrikeModeProperty)
{
Caret.UpdateIfVisible();
}
}
/// <summary>
/// Gets the requested service.
/// </summary>
/// <returns>Returns the requested service instance, or null if the service cannot be found.</returns>
public virtual object GetService(Type serviceType)
{
return TextView.GetService(serviceType);
}
/// <summary>
/// Occurs when text inside the TextArea was copied.
/// </summary>
public event EventHandler<TextEventArgs> TextCopied;
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; }
remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; }
}
internal void OnTextCopied(TextEventArgs e)
{
TextCopied?.Invoke(this, e);
}
public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>();
bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool);
Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size);
Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size);
Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size);
Vector IScrollable.Offset
{
get => _logicalScrollable?.Offset ?? default(Vector);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.Offset = value;
}
}
}
Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size);
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanHorizontallyScroll = value;
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _logicalScrollable?.CanVerticallyScroll ?? default(bool);
set
{
if (_logicalScrollable != null)
{
_logicalScrollable.CanVerticallyScroll = value;
}
}
}
public bool BringIntoView(IControl target, Rect targetRect) =>
_logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool);
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
=> _logicalScrollable?.GetControlInDirection(direction, from);
public void RaiseScrollInvalidated(EventArgs e)
{
_logicalScrollable?.RaiseScrollInvalidated(e);
}
private class TextAreaTextInputMethodClient : ITextInputMethodClient
{
private TextArea _textArea;
public TextAreaTextInputMethodClient()
{
}
public event EventHandler CursorRectangleChanged;
public event EventHandler TextViewVisualChanged;
public event EventHandler SurroundingTextChanged;
public Rect CursorRectangle
{
get
{
if(_textArea == null)
{
return Rect.Empty;
}
var transform = _textArea.TextView.TransformToVisual(_textArea);
if (transform == null)
{
return default;
}
var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value);
return rect;
}
}
public IVisual TextViewVisual => _textArea;
public bool SupportsPreedit => false;
public bool SupportsSurroundingText => true;
public TextInputMethodSurroundingText SurroundingText
{
get
{
if(_textArea == null)
{
return default;
}
var lineIndex = _textArea.Caret.Line;
var position = _textArea.Caret.Position;
var documentLine = _textArea.Document.GetLineByNumber(lineIndex);
var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length);
return new TextInputMethodSurroundingText
{
AnchorOffset = 0,
CursorOffset = position.Column,
Text = text
};
}
}
public void SetTextArea(TextArea textArea)
{
if(_textArea != null)
{
_textArea.Caret.PositionChanged -= Caret_PositionChanged;
_textArea.SelectionChanged -= TextArea_SelectionChanged;
}
_textArea = textArea;
if(_textArea != null)
{
_textArea.Caret.PositionChanged += Caret_PositionChanged;
_textArea.SelectionChanged += TextArea_SelectionChanged;
}
TextViewVisualChanged?.Invoke(this, EventArgs.Empty);
CursorRectangleChanged?.Invoke(this, EventArgs.Empty);
}
private void Caret_PositionChanged(object sender, EventArgs e)
{
CursorRectangleChanged?.Invoke(this, e);
}
private void TextArea_SelectionChanged(object sender, EventArgs e)
{
SurroundingTextChanged?.Invoke(this, e);
}
public void SelectInSurroundingText(int start, int end)
{
if(_textArea == null)
{
return;
}
var selection = _textArea.Selection;
_textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint(
new TextViewPosition(selection.StartPosition.Line, start),
new TextViewPosition(selection.StartPosition.Line, end));
}
public void SetPreeditText(string text)
{
}
}
}
/// <summary>
/// EventArgs with text.
/// </summary>
public class TextEventArgs : EventArgs
{
/// <summary>
/// Gets the text.
/// </summary>
public string Text { get; }
/// <summary>
/// Creates a new TextEventArgs instance.
/// </summary>
public TextEventArgs(string text)
{
Text = text ?? throw new ArgumentNullException(nameof(text));
}
}
}
<MSG> Fix Ctrl+Backspace special char
<DFF> @@ -770,7 +770,7 @@ namespace AvaloniaEdit.Editing
base.OnTextInput(e);
if (!e.Handled && Document != null)
{
- if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b")
+ if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f")
{
// TODO: check this
// ASCII 0x1b = ESC.
| 1 | Fix Ctrl+Backspace special char | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062614 | <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-сell,
.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-align-right,
.jsgrid-align-right input,
.jsgrid-align-right textarea,
.jsgrid-align-right select {
text-align: right;
}
.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> Merge pull request #932 from kstenschke/patch-2
Styling: Fix encoding issue for `jsgrid-cell`.
<DFF> @@ -42,7 +42,7 @@
padding: 0.5em 0.5em;
}
-.jsgrid-сell,
+.jsgrid-cell,
.jsgrid-header-cell {
box-sizing: border-box;
}
| 1 | Merge pull request #932 from kstenschke/patch-2 | 1 | .css | css | mit | tabalinas/jsgrid |
10062615 | <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-сell,
.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-align-right,
.jsgrid-align-right input,
.jsgrid-align-right textarea,
.jsgrid-align-right select {
text-align: right;
}
.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> Merge pull request #932 from kstenschke/patch-2
Styling: Fix encoding issue for `jsgrid-cell`.
<DFF> @@ -42,7 +42,7 @@
padding: 0.5em 0.5em;
}
-.jsgrid-сell,
+.jsgrid-cell,
.jsgrid-header-cell {
box-sizing: border-box;
}
| 1 | Merge pull request #932 from kstenschke/patch-2 | 1 | .css | css | mit | tabalinas/jsgrid |
10062616 | <NME> fruitmachine.js
<BEF> /*jslint browser:true, node:true*/
/**
* FruitMachine
*
* Renders layouts/modules from a basic layout definition.
* If views require custom interactions devs can extend
* the basic functionality.
*
* @version 0.3.3
* @copyright The Financial Times Limited [All Rights Reserved]
* @author Wilson Page <[email protected]>
*/
'use strict';
/**
* Module Dependencies
*/
var mod = require('./module');
var define = require('./define');
var utils = require('utils');
var events = require('evt');
/**
* Creates a fruitmachine
*
* Options:
*
* - `Model` A model constructor to use (must have `.toJSON()`)
*
* @param {Object} options
*/
module.exports = function(options) {
/**
* Shortcut method for
* creating lazy views.
*
* @param {Object} options
* @return {Module}
*/
function fm(options) {
var Module = fm.modules[options.module];
if (Module) {
return new Module(options);
}
throw new Error("Unable to find module '" + options.module + "'");
}
fm.create = module.exports;
fm.Model = options.Model;
fm.Events = events;
fm.Module = mod(fm);
fm.define = define(fm);
fm.util = utils;
fm.modules = {};
fm.config = {
templateIterator: 'children',
templateInstance: 'child'
};
// Mixin events and return
return events(fm);
};
});
},
children: function(name) {
return name ? this._lookup[name] : this._children;
},
/**
<MSG> More advanced View#children() method with recursion and looping options
<DFF> @@ -414,8 +414,50 @@
});
},
- children: function(name) {
- return name ? this._lookup[name] : this._children;
+ /**
+ * Allows three ways to return
+ * a view's children and direct
+ * children, depending on arguments
+ * passed.
+ *
+ * Example:
+ *
+ * // Return all direct children
+ * view.children();
+ *
+ * // Return all descendant children
+ * // that match query.
+ * view.children('orange');
+ *
+ * // Loop direct children like forEach style.
+ * // Not sure if this is neccessary or not?
+ * // Could be depricated.
+ * view.children(function(child) { ... });
+ *
+ * @param {undefined|String|Function} query
+ * @return {Array}
+ */
+ children: function(query) {
+
+ // If no argument is passd,
+ // return all direct children.
+ if (!query) return this._children;
+
+ // If a function is passed, loop the children
+ if ('function' === typeof query) return this.each(query);
+
+ // Get the direct children
+ // that match this query
+ var list = this._lookup[query] || [];
+
+ // Then loop each child and run the
+ // same opperation, appending the result
+ // onto the list.
+ this.each(function(view) {
+ list = list.concat(view.children(query));
+ });
+
+ return list;
},
/**
| 44 | More advanced View#children() method with recursion and looping options | 2 | .js | js | mit | ftlabs/fruitmachine |
10062617 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062618 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062619 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062620 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062621 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062622 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062623 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062624 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062625 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062626 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062627 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062628 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062629 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062630 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062631 | <NME> TextFormatterFactory.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Media;
using Avalonia.Media.TextFormatting;
namespace AvaloniaEdit.Utils
{
/// <summary>
/// Creates TextFormatter instances that with the correct TextFormattingMode, if running on .NET 4.0.
/// </summary>
static class TextFormatterFactory
{
/// <summary>
/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
/// </summary>
public static TextFormatter Create(Control owner)
{
return TextFormatter.Current;
}
/// <summary>
/// Creates formatted text.
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
public static FormattedText CreateFormattedText(Control element, string text, Typeface typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (text == null)
throw new ArgumentNullException(nameof(text));
if (typeface == default)
typeface = element.CreateTypeface();
if (emSize == null)
emSize = TextElement.GetFontSize(element);
if (foreground == null)
foreground = TextElement.GetForeground(element);
return new FormattedText(
text,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
emSize.Value,
foreground);
}
}
}
<MSG> prep custom font pr./
<DFF> @@ -43,7 +43,7 @@ namespace AvaloniaEdit.Utils
/// <param name="emSize">The font size. If this parameter is null, the font size of the <paramref name="element"/> will be used.</param>
/// <param name="foreground">The foreground color. If this parameter is null, the foreground of the <paramref name="element"/> will be used.</param>
/// <returns>A FormattedText object using the specified settings.</returns>
- public static FormattedText CreateFormattedText(Control element, string text, string typeface, double? emSize, IBrush foreground)
+ public static FormattedText CreateFormattedText(Control element, string text, Avalonia.Media.FontFamily typeface, double? emSize, IBrush foreground)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
| 1 | prep custom font pr./ | 1 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10062632 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062633 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062634 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062635 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062636 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062637 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062638 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062639 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062640 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062641 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062642 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062643 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062644 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062645 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062646 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
<Style Selector="search|SearchPanel Button:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}"/>
</Style>
<Style Selector="search|SearchPanel">
<Setter Property="BorderThickness"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> Merge pull request #156 from AvaloniaUI/fix-hidden-search-results
Fixed search results appearing under the search panel
<DFF> @@ -40,7 +40,7 @@
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
- <Border BorderThickness="{TemplateBinding BorderThickness}"
+ <Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
| 1 | Merge pull request #156 from AvaloniaUI/fix-hidden-search-results | 1 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10062647 | <NME> it.js
<BEF> ADDFILE
<MSG> Merge pull request #634 from saxcbr/master
i18n: Add Italian locale
<DFF> @@ -0,0 +1,47 @@
+(function(jsGrid) {
+
+ jsGrid.locales.it = {
+ grid: {
+ noDataContent: "Nessun risultato",
+ deleteConfirm: "Sei sicuro ?",
+ pagerFormat: "Pagine: {first} {prev} {pages} {next} {last} {pageIndex} di {pageCount}",
+ pagePrevText: "<",
+ pageNextText: ">",
+ pageFirstText: "<<",
+ pageLastText: ">>",
+ loadMessage: "Attendere prego ...",
+ invalidMessage: "Dati non validi!"
+ },
+
+ loadIndicator: {
+ message: "Caricamento in corso..."
+ },
+
+ fields: {
+ control: {
+ searchModeButtonTooltip: "Modallità ricerca",
+ insertModeButtonTooltip: "Modalità inserimento",
+ editButtonTooltip: "Modifica",
+ deleteButtonTooltip: "Cancella",
+ searchButtonTooltip: "Cerca",
+ clearFilterButtonTooltip: "Cancella filtri",
+ insertButtonTooltip: "Inserisci",
+ updateButtonTooltip: "Aggiorna",
+ cancelEditButtonTooltip: "Annulla"
+ }
+ },
+
+ validators: {
+ required: { message: "Campo richiesto" },
+ rangeLength: { message: "La dimensione del valore del campo è fuori dell'intervallo definito" },
+ minLength: { message: "Il valore del campo è troppo breve" },
+ maxLength: { message: "Il valore del campo è troppo lungo" },
+ pattern: { message: "Il valore del campo non corrisponde alla configurazione definita" },
+ range: { message: "Il valore del campo è al di fuori del range definito" },
+ min: { message: "Il valore del campo è troppo piccolo" },
+ max: { message: "Il valore del campo è troppo grande" }
+ }
+ };
+
+}(jsGrid, jQuery));
+
| 47 | Merge pull request #634 from saxcbr/master | 0 | .js | js | mit | tabalinas/jsgrid |
10062648 | <NME> it.js
<BEF> ADDFILE
<MSG> Merge pull request #634 from saxcbr/master
i18n: Add Italian locale
<DFF> @@ -0,0 +1,47 @@
+(function(jsGrid) {
+
+ jsGrid.locales.it = {
+ grid: {
+ noDataContent: "Nessun risultato",
+ deleteConfirm: "Sei sicuro ?",
+ pagerFormat: "Pagine: {first} {prev} {pages} {next} {last} {pageIndex} di {pageCount}",
+ pagePrevText: "<",
+ pageNextText: ">",
+ pageFirstText: "<<",
+ pageLastText: ">>",
+ loadMessage: "Attendere prego ...",
+ invalidMessage: "Dati non validi!"
+ },
+
+ loadIndicator: {
+ message: "Caricamento in corso..."
+ },
+
+ fields: {
+ control: {
+ searchModeButtonTooltip: "Modallità ricerca",
+ insertModeButtonTooltip: "Modalità inserimento",
+ editButtonTooltip: "Modifica",
+ deleteButtonTooltip: "Cancella",
+ searchButtonTooltip: "Cerca",
+ clearFilterButtonTooltip: "Cancella filtri",
+ insertButtonTooltip: "Inserisci",
+ updateButtonTooltip: "Aggiorna",
+ cancelEditButtonTooltip: "Annulla"
+ }
+ },
+
+ validators: {
+ required: { message: "Campo richiesto" },
+ rangeLength: { message: "La dimensione del valore del campo è fuori dell'intervallo definito" },
+ minLength: { message: "Il valore del campo è troppo breve" },
+ maxLength: { message: "Il valore del campo è troppo lungo" },
+ pattern: { message: "Il valore del campo non corrisponde alla configurazione definita" },
+ range: { message: "Il valore del campo è al di fuori del range definito" },
+ min: { message: "Il valore del campo è troppo piccolo" },
+ max: { message: "Il valore del campo è troppo grande" }
+ }
+ };
+
+}(jsGrid, jQuery));
+
| 47 | Merge pull request #634 from saxcbr/master | 0 | .js | js | mit | tabalinas/jsgrid |
10062649 | <NME> Directory.Build.props
<BEF> <Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.12</AvaloniaVersion>
<TextMateSharpVersion>1.0.31</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
<Version>0.10.12.2</Version>
</PropertyGroup>
</Project>
<MSG> Update TextMateSharpVersion to 1.0.34
It includes:
- Fixes Operations that change non-concurrent collections must have exclusive access: https://github.com/danipen/TextMateSharp/pull/16
- Use .net 6.0 for build the nugets: https://github.com/danipen/TextMateSharp/pull/17
<DFF> @@ -3,7 +3,7 @@
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<AvaloniaVersion>0.10.12</AvaloniaVersion>
- <TextMateSharpVersion>1.0.31</TextMateSharpVersion>
+ <TextMateSharpVersion>1.0.34</TextMateSharpVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
<Version>0.10.12.2</Version>
</PropertyGroup>
| 1 | Update TextMateSharpVersion to 1.0.34 | 1 | .props | Build | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.