
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ActiproSoftware.Windows.Controls.SyntaxEditor;
using System.Windows.Media;
using System.Globalization;
using System.Windows.Controls.Primitives;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using Connexion.Core;
using ActiproSoftware.Text;
namespace Connexion.Device
{
public class AutoHeightSyntaxEditor : SyntaxEditor
{
public AutoHeightSyntaxEditor()
{
VerticalScrollBarVisibility = System.Windows.Controls.ScrollBarVisibility.Disabled;
HorizontalScrollBarVisibility = System.Windows.Controls.ScrollBarVisibility.Disabled;
DocumentTextChanged += (o, e) => PerformAutoSizeHeight();
LayoutUpdated += (o, e) => PerformAutoSizeHeight();
PreviewMouseWheel += (o, e) =>
{
e.Handled = true;
var e2 = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
e2.RoutedEvent = UIElement.MouseWheelEvent;
e2.Source = o;
var parent = WPFHelpers.GetParentOfType(this, typeof(ScrollViewer)) as ScrollViewer;
if (parent != null)
parent.RaiseEvent(e2);
};
}
public void PerformAutoSizeHeight()
{
if (!string.IsNullOrEmpty(Text))
{
ActiveView.Scroller.ScrollToDocumentStart();
// calc margin widths
double marginWidth = 0;
foreach (var margin in ActiveView.Margins)
{
marginWidth += margin.VisualElement.ActualWidth;
}
var collapsedRegions = ActiveView.CollapsedRegionManager.GetCollapsedRanges(new TextSnapshotRange(ActiveView.CurrentSnapshot, 0, ActiveView.CurrentSnapshot.Length));
StringBuilder text = null;
bool endsInNewLine = false;
if (collapsedRegions != null && collapsedRegions.Count > 0)
{
text = new StringBuilder(ActiveView.CurrentSnapshot.GetText(LineTerminator.CarriageReturn));
foreach (var collapsedRgn in collapsedRegions.OrderByDescending(c => c.StartOffset))
{
text.Remove(collapsedRgn.StartOffset, collapsedRgn.Length);
}
endsInNewLine = text[text.Length - 1] == '\r';
}
else
{
endsInNewLine = Text.EndsWith("\r") || Text.EndsWith("\n");
}
Typeface typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
FormattedText formattedText = new FormattedText(text == null ? Text : text.ToString(), CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, typeface, FontSize, Brushes.Black)
{
MaxTextWidth = Math.Max(0, ActualWidth - (Margin.Left + Margin.Right + Padding.Left + Padding.Right + marginWidth)),
LineHeight = 16, // <-- This should be based off the current font + some padding value. Actipro property?
Trimming = TextTrimming.None,
};
Height = formattedText.Height + (endsInNewLine ? formattedText.LineHeight : 0) + (Padding.Top + Padding.Bottom);
}
}
}
}