A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Merged PR 96: Added the text editor
Etienne Baudoux113f08d88bb3
diff --git a/src/Directory.Build.props b/src/Directory.Build.propsindex 40711d9b6..fd502b034 100644--- a/src/Directory.Build.props+++ b/src/Directory.Build.props@@ -38,10 +38,14 @@</PropertyGroup><PropertyGroup>+ <Nuget_ColorCodeUwp>2.0.9</Nuget_ColorCodeUwp>+ <Nuget_DiffPlex>1.7.0</Nuget_DiffPlex>+ <Nuget_DirectN>1.9.1</Nuget_DirectN><NuGet_MicrosoftNETCoreUniversalWindowsPlatform>6.2.12</NuGet_MicrosoftNETCoreUniversalWindowsPlatform><NuGet_MicrosoftToolkitMvvm>7.0.2</NuGet_MicrosoftToolkitMvvm>- <NuGet_MicrosoftUIXaml>2.6.2</NuGet_MicrosoftUIXaml><Nuget_MicrosoftToolkitUwpUIBehaviors>7.0.2</Nuget_MicrosoftToolkitUwpUIBehaviors>+ <Nuget_MicrosoftToolkitUwpUIControls>7.0.2</Nuget_MicrosoftToolkitUwpUIControls>+ <NuGet_MicrosoftUIXaml>2.6.2</NuGet_MicrosoftUIXaml><NuGet_MicrosoftWindowsSDKBuildTools>10.0.19041.8</NuGet_MicrosoftWindowsSDKBuildTools><NuGet_MSTestTestAdapter>2.1.1</NuGet_MSTestTestAdapter><NuGet_MSTestTestFramework>2.1.1</NuGet_MSTestTestFramework>diff --git a/src/dev/def/DevTools.Core/Settings/PredefinedSettings.cs b/src/dev/def/DevTools.Core/Settings/PredefinedSettings.csindex 5c0e430de..28b6089cf 100644--- a/src/dev/def/DevTools.Core/Settings/PredefinedSettings.cs+++ b/src/dev/def/DevTools.Core/Settings/PredefinedSettings.cs@@ -30,5 +30,32 @@ namespace DevTools.Core.Settingsname: nameof(TextEditorFont),isRoaming: true,defaultValue: "CascadiaMono");++ /// <summary>+ /// Whether the text in the text editor should wrap.+ /// </summary>+ public static readonly SettingDefinition<bool> TextEditorTextWrapping+ = new(+ name: nameof(TextEditorTextWrapping),+ isRoaming: true,+ defaultValue: false);++ /// <summary>+ /// Whether the line numbers should be displayed in the text editor.+ /// </summary>+ public static readonly SettingDefinition<bool> TextEditorLineNumbers+ = new(+ name: nameof(TextEditorLineNumbers),+ isRoaming: true,+ defaultValue: true);++ /// <summary>+ /// Whether the line where the caret is should be highlighted in the text editor.+ /// </summary>+ public static readonly SettingDefinition<bool> TextEditorHighlightCurrentLine+ = new(+ name: nameof(TextEditorHighlightCurrentLine),+ isRoaming: true,+ defaultValue: true);}}diff --git a/src/dev/impl/DevTools.Common/DevTools.Common.csproj b/src/dev/impl/DevTools.Common/DevTools.Common.csprojindex 648a7673b..0b32b2a23 100644--- a/src/dev/impl/DevTools.Common/DevTools.Common.csproj+++ b/src/dev/impl/DevTools.Common/DevTools.Common.csproj@@ -80,6 +80,13 @@<AutoGen>True</AutoGen><DesignTime>True</DesignTime></Compile>+ <Compile Include="UI\Controls\TextEditor\CommandHandlerResult.cs" />+ <Compile Include="UI\Controls\TextEditor\ICommandHandler.cs" />+ <Compile Include="UI\Controls\TextEditor\IKeyboardCommand.cs" />+ <Compile Include="UI\Controls\TextEditor\KeyboardCommand.cs" />+ <Compile Include="UI\Controls\TextEditor\KeyboardCommandHandler.cs" />+ <Compile Include="UI\Controls\TextEditor\TextFormatter.cs" />+ <Compile Include="UI\Extensions\ColorHelper.cs" /><Compile Include="UI\Controls\CustomPathIcon.cs" /><Compile Include="UI\Controls\ExpandableSettingControl.xaml.cs"><DependentUpon>ExpandableSettingControl.xaml</DependentUpon>@@ -87,13 +94,16 @@<Compile Include="UI\Controls\ExpandableSettingHeaderControl.xaml.cs"><DependentUpon>ExpandableSettingHeaderControl.xaml</DependentUpon></Compile>+ <Compile Include="UI\Controls\TextEditor\TextEditor.cs" /><Compile Include="UI\Converters\EnumToBooleanConverter.cs" /><Compile Include="UI\Converters\EnumToThicknessConverter.cs" /><Compile Include="UI\Converters\BooleanToVisibilityConverter.cs" /><Compile Include="UI\Converters\DoubleToGridLengthConverter.cs" /><Compile Include="UI\Converters\InvertedBooleanConverter.cs" /><Compile Include="UI\Converters\NullToBooleanConverter.cs" />+ <Compile Include="UI\Extensions\Axis.cs" /><Compile Include="UI\Extensions\HighlighterExtension.cs" />+ <Compile Include="UI\Extensions\ScrollViewerExtensions.cs" /><Content Include="Assets\Icons\Idea.svg" /><Content Include="LanguageManager.tt"><Generator>TextTemplatingFileGenerator</Generator>@@ -102,8 +112,12 @@<PRIResource Include="Strings\en\MainPage.resw" /></ItemGroup><ItemGroup>+ <PackageReference Include="ColorCode.UWP" Version="$(Nuget_ColorCodeUwp)" />+ <PackageReference Include="DiffPlex" Version="$(Nuget_DiffPlex)" />+ <PackageReference Include="DirectN" Version="$(Nuget_DirectN)" /><PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="$(NuGet_MicrosoftNETCoreUniversalWindowsPlatform)" /><PackageReference Include="Microsoft.Toolkit.Mvvm" Version="$(NuGet_MicrosoftToolkitMvvm)" />+ <PackageReference Include="Microsoft.Toolkit.Uwp.UI.Controls" Version="$(Nuget_MicrosoftToolkitUwpUIControls)" /><PackageReference Include="Microsoft.UI.Xaml" Version="$(NuGet_MicrosoftUIXaml)" /></ItemGroup><ItemGroup>@@ -137,6 +151,10 @@<PRIResource Include="Strings\en\Settings.resw" /></ItemGroup><ItemGroup>+ <ProjectReference Include="..\..\def\DevTools.Core\DevTools.Core.csproj">+ <Project>{ef6a6707-44f2-4e76-98b8-11c9b40adc7e}</Project>+ <Name>DevTools.Core</Name>+ </ProjectReference><ProjectReference Include="..\..\def\DevTools.Providers\DevTools.Providers.csproj"><Project>{ada9988b-e19b-4ee5-9162-dab3b12bcf9e}</Project><Name>DevTools.Providers</Name>@@ -154,6 +172,7 @@<ItemGroup><Content Include="Assets\CascadiaMono.ttf" /></ItemGroup>+ <ItemGroup /><Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" /><!-- To modify your build process, add your task inside one of the targets below and uncomment it.Other similar extension points exist, see Microsoft.Common.targets.diff --git a/src/dev/impl/DevTools.Common/LanguageManager.cs b/src/dev/impl/DevTools.Common/LanguageManager.csindex 464c6dc9e..37c76bdbe 100644--- a/src/dev/impl/DevTools.Common/LanguageManager.cs+++ b/src/dev/impl/DevTools.Common/LanguageManager.cs@@ -107,6 +107,36 @@ namespace DevTools.Common{private readonly ResourceLoader _resources = ResourceLoader.GetForViewIndependentUse("DevTools.Common/Common");+ /// <summary>+ /// Gets the resource Copy.+ /// </summary>+ public string Copy => _resources.GetString("Copy");++ /// <summary>+ /// Gets the resource Cut.+ /// </summary>+ public string Cut => _resources.GetString("Cut");++ /// <summary>+ /// Gets the resource Delete.+ /// </summary>+ public string Delete => _resources.GetString("Delete");++ /// <summary>+ /// Gets the resource Paste.+ /// </summary>+ public string Paste => _resources.GetString("Paste");++ /// <summary>+ /// Gets the resource Redo.+ /// </summary>+ public string Redo => _resources.GetString("Redo");++ /// <summary>+ /// Gets the resource SelectAll.+ /// </summary>+ public string SelectAll => _resources.GetString("SelectAll");+/// <summary>/// Gets the resource ToggleSwitchOff./// </summary>@@ -116,6 +146,11 @@ namespace DevTools.Common/// Gets the resource ToggleSwitchOn./// </summary>public string ToggleSwitchOn => _resources.GetString("ToggleSwitchOn");++ /// <summary>+ /// Gets the resource Undo.+ /// </summary>+ public string Undo => _resources.GetString("Undo");}public class JsonFormatterStrings : ObservableObject@@ -192,11 +227,31 @@ namespace DevTools.Common/// </summary>public string Font => _resources.GetString("Font");+ /// <summary>+ /// Gets the resource HighlightCurrentLine.+ /// </summary>+ public string HighlightCurrentLine => _resources.GetString("HighlightCurrentLine");++ /// <summary>+ /// Gets the resource HighlightCurrentLineDescription.+ /// </summary>+ public string HighlightCurrentLineDescription => _resources.GetString("HighlightCurrentLineDescription");+/// <summary>/// Gets the resource Light./// </summary>public string Light => _resources.GetString("Light");+ /// <summary>+ /// Gets the resource LineNumbers.+ /// </summary>+ public string LineNumbers => _resources.GetString("LineNumbers");++ /// <summary>+ /// Gets the resource LineNumbersDescription.+ /// </summary>+ public string LineNumbersDescription => _resources.GetString("LineNumbersDescription");+/// <summary>/// Gets the resource SmartDetection./// </summary>@@ -221,5 +276,10 @@ namespace DevTools.Common/// Gets the resource UseSystemSettings./// </summary>public string UseSystemSettings => _resources.GetString("UseSystemSettings");++ /// <summary>+ /// Gets the resource WordWrap.+ /// </summary>+ public string WordWrap => _resources.GetString("WordWrap");}}\ No newline at end of filediff --git a/src/dev/impl/DevTools.Common/Strings/en/Common.resw b/src/dev/impl/DevTools.Common/Strings/en/Common.reswindex 7087289f4..084d1f230 100644--- a/src/dev/impl/DevTools.Common/Strings/en/Common.resw+++ b/src/dev/impl/DevTools.Common/Strings/en/Common.resw@@ -117,10 +117,31 @@<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>+ <data name="Copy" xml:space="preserve">+ <value>Copy</value>+ </data>+ <data name="Cut" xml:space="preserve">+ <value>Cut</value>+ </data>+ <data name="Delete" xml:space="preserve">+ <value>Delete</value>+ </data>+ <data name="Paste" xml:space="preserve">+ <value>Paste</value>+ </data>+ <data name="Redo" xml:space="preserve">+ <value>Redo</value>+ </data>+ <data name="SelectAll" xml:space="preserve">+ <value>Select all</value>+ </data><data name="ToggleSwitchOff" xml:space="preserve"><value>Off</value></data><data name="ToggleSwitchOn" xml:space="preserve"><value>On</value></data>+ <data name="Undo" xml:space="preserve">+ <value>Undo</value>+ </data></root>\ No newline at end of filediff --git a/src/dev/impl/DevTools.Common/Strings/en/Settings.resw b/src/dev/impl/DevTools.Common/Strings/en/Settings.reswindex 7c5d12f0a..76cf4ee7c 100644--- a/src/dev/impl/DevTools.Common/Strings/en/Settings.resw+++ b/src/dev/impl/DevTools.Common/Strings/en/Settings.resw@@ -138,9 +138,21 @@<data name="Font" xml:space="preserve"><value>Font</value></data>+ <data name="HighlightCurrentLine" xml:space="preserve">+ <value>Highlight current line</value>+ </data>+ <data name="HighlightCurrentLineDescription" xml:space="preserve">+ <value>Change the background color of the current line so it's more visible</value>+ </data><data name="Light" xml:space="preserve"><value>Light</value></data>+ <data name="LineNumbers" xml:space="preserve">+ <value>Line numbers</value>+ </data>+ <data name="LineNumbersDescription" xml:space="preserve">+ <value>Display line numbers in the text editor</value>+ </data><data name="SmartDetection" xml:space="preserve"><value>Smart detection</value></data>@@ -156,4 +168,7 @@<data name="UseSystemSettings" xml:space="preserve"><value>Use system settings</value></data>+ <data name="WordWrap" xml:space="preserve">+ <value>Wrap word</value>+ </data></root>\ No newline at end of filediff --git a/src/dev/impl/DevTools.Common/Themes/Generic.xaml b/src/dev/impl/DevTools.Common/Themes/Generic.xamlindex e7954f5c5..1dedb74f4 100644--- a/src/dev/impl/DevTools.Common/Themes/Generic.xaml+++ b/src/dev/impl/DevTools.Common/Themes/Generic.xaml@@ -2,7 +2,21 @@xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:controls="using:DevTools.Common.UI.Controls"+ xmlns:textEditor="using:DevTools.Common.UI.Controls.TextEditor"xmlns:common="using:DevTools.Common">++ <ResourceDictionary.ThemeDictionaries>+ <ResourceDictionary x:Key="Light">+ <SolidColorBrush x:Key="TextEditorForeground" Color="Black"/>+ </ResourceDictionary>+ <ResourceDictionary x:Key="Dark">+ <SolidColorBrush x:Key="TextEditorForeground" Color="#F0F0F0"/>+ </ResourceDictionary>+ <ResourceDictionary x:Key="HighContrast">+ <SolidColorBrush x:Key="TextEditorForeground" Color="{ThemeResource TextControlForeground}"/>+ </ResourceDictionary>+ </ResourceDictionary.ThemeDictionaries>+<common:LanguageManager x:Key="LanguageManager"/><Style TargetType="controls:CustomPathIcon">@@ -20,4 +34,247 @@<Setter Property="OnContent" Value="{Binding Instance.Common.ToggleSwitchOn, Source={StaticResource LanguageManager}}"/><Setter Property="OffContent" Value="{Binding Instance.Common.ToggleSwitchOff, Source={StaticResource LanguageManager}}"/></Style>++ <Style TargetType="textEditor:TextEditor">+ <Setter Property="Foreground" Value="{ThemeResource TextEditorForeground}"/>+ <Setter Property="Background" Value="{ThemeResource TextControlBackground}"/>+ <Setter Property="SelectionHighlightColor" Value="{ThemeResource TextControlSelectionHighlightColor}"/>+ <Setter Property="BorderBrush" Value="{ThemeResource TextControlBorderBrush}"/>+ <Setter Property="BorderThickness" Value="{ThemeResource TextControlBorderThemeThickness}"/>+ <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>+ <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>+ <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Enabled"/>+ <Setter Property="ScrollViewer.VerticalScrollMode" Value="Enabled"/>+ <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>+ <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>+ <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>+ <Setter Property="TextWrapping" Value="NoWrap"/>+ <Setter Property="Padding" Value="0"/>+ <Setter Property="UseSystemFocusVisuals" Value="{ThemeResource IsApplicationFocusVisualKindReveal}"/>+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="RichEditBox">+ <Grid>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto"/>+ <RowDefinition Height="*"/>+ <RowDefinition Height="Auto"/>+ </Grid.RowDefinitions>+ <VisualStateManager.VisualStateGroups>+ <VisualStateGroup x:Name="CommonStates">+ <VisualState x:Name="Disabled">+ <Storyboard>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="HeaderContentPresenter" Storyboard.TargetProperty="Foreground">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlHeaderForegroundDisabled}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundDisabled}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushDisabled}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundDisabled}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundDisabled}"/>+ </ObjectAnimationUsingKeyFrames>+ </Storyboard>+ </VisualState>+ <VisualState x:Name="Normal"/>+ <VisualState x:Name="PointerOver">+ <Storyboard>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushPointerOver}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundPointerOver}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundPointerOver}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundPointerOver}"/>+ </ObjectAnimationUsingKeyFrames>+ </Storyboard>+ </VisualState>+ <VisualState x:Name="Focused">+ <Storyboard>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="PlaceholderTextContentPresenter" Storyboard.TargetProperty="Foreground">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlPlaceholderForegroundFocused}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="Background">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBackgroundFocused}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="BorderElement" Storyboard.TargetProperty="BorderBrush">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlBorderBrushFocused}"/>+ </ObjectAnimationUsingKeyFrames>+ <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">+ <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource TextControlForegroundFocused}"/>+ </ObjectAnimationUsingKeyFrames>+ </Storyboard>+ </VisualState>+ </VisualStateGroup>+ </VisualStateManager.VisualStateGroups>+ <ContentPresenter+ x:Name="HeaderContentPresenter"+ ContentTemplate="{TemplateBinding HeaderTemplate}"+ Content="{TemplateBinding Header}"+ FontWeight="Normal"+ Foreground="{ThemeResource TextControlHeaderForeground}"+ Margin="{ThemeResource RichEditBoxTopHeaderMargin}"+ Grid.Row="0"+ TextWrapping="Wrap"+ VerticalAlignment="Top"+ Visibility="Collapsed"+ x:DeferLoadStrategy="Lazy">+ </ContentPresenter>+ <Border+ x:Name="BorderElement"+ Background="{TemplateBinding Background}"+ BorderThickness="{TemplateBinding BorderThickness}"+ BorderBrush="{TemplateBinding BorderBrush}"+ CornerRadius="{TemplateBinding CornerRadius}"+ MinHeight="{ThemeResource TextControlThemeMinHeight}"+ MinWidth="{ThemeResource TextControlThemeMinWidth}"+ Grid.Row="1"/>+ <Grid x:Name="RootGrid" Grid.Row="1">+ <Grid.ColumnDefinitions>+ <ColumnDefinition x:Name="LineNumberColumnDefinition" Width="Auto"/>+ <ColumnDefinition x:Name="TextEditorColumnDefinition" Width="*"/>+ </Grid.ColumnDefinitions>+ <Canvas x:Name="LineHighlighterAndIndicatorCanvas" Grid.ColumnSpan="2">+ <Border+ x:Name="LineIndicator"+ BorderBrush="{StaticResource SystemControlForegroundAccentBrush}"+ Visibility="Collapsed"/>+ <Grid+ x:Name="LineHighlighter"+ Background="{ThemeResource SystemControlBackgroundListLowBrush}"+ Opacity="0.65"+ BorderThickness="0"+ Visibility="Collapsed"/>+ </Canvas>+ <Grid+ x:Name="LineNumberGrid"+ Grid.Column="0"+ BorderThickness="0,0,0,0"+ BorderBrush="{ThemeResource SystemControlBackgroundTransparentRevealBorderBrush}">+ <Canvas x:Name="LineNumberCanvas"/>+ </Grid>+ <Grid Grid.Column="1">+ <ScrollViewer+ x:Name="ContentElement"+ AutomationProperties.AccessibilityView="Raw"+ HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"+ HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"+ IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"+ IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"+ IsTabStop="False"+ IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"+ Margin="{TemplateBinding BorderThickness}"+ Padding="{TemplateBinding Padding}"+ VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"+ VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"+ ZoomMode="Disabled"/>+ </Grid>+ </Grid>+ <TextBlock+ x:Name="PlaceholderTextContentPresenter"+ Foreground="{ThemeResource TextControlPlaceholderForeground}"+ IsHitTestVisible="False"+ Margin="{TemplateBinding BorderThickness}"+ Padding="{TemplateBinding Padding}"+ Grid.Row="1"+ Text="{TemplateBinding PlaceholderText}"+ TextWrapping="{TemplateBinding TextWrapping}"+ TextAlignment="{TemplateBinding TextAlignment}"+ OpticalMarginAlignment="TrimSideBearings"/>+ <ContentPresenter+ x:Name="DescriptionPresenter"+ AutomationProperties.AccessibilityView="Raw"+ Content="{TemplateBinding Description}"+ Foreground="{ThemeResource SystemControlDescriptionTextForegroundBrush}"+ Grid.Row="2"+ x:Load="False"/>+ </Grid>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ <Setter Property="ContextFlyout">+ <Setter.Value>+ <MenuFlyout>+ <MenuFlyoutItem+ Text="{Binding Instance.Common.Cut, Source={StaticResource LanguageManager}}"+ Command="{Binding CutCommand}">+ <MenuFlyoutItem.Icon>+ <FontIcon Glyph="" />+ </MenuFlyoutItem.Icon>+ <MenuFlyoutItem.KeyboardAccelerators>+ <KeyboardAccelerator Key="X" Modifiers="Control" IsEnabled="False"/>+ </MenuFlyoutItem.KeyboardAccelerators>+ </MenuFlyoutItem>+ <MenuFlyoutItem+ Text="{Binding Instance.Common.Copy, Source={StaticResource LanguageManager}}"+ Command="{Binding CopyCommand}">+ <MenuFlyoutItem.Icon>+ <FontIcon Glyph="" />+ </MenuFlyoutItem.Icon>+ <MenuFlyoutItem.KeyboardAccelerators>+ <KeyboardAccelerator Key="C" Modifiers="Control" IsEnabled="False"/>+ </MenuFlyoutItem.KeyboardAccelerators>+ </MenuFlyoutItem>+ <MenuFlyoutItem+ Text="{Binding Instance.Common.Paste, Source={StaticResource LanguageManager}}"+ Command="{Binding PasteCommand}">+ <MenuFlyoutItem.Icon>+ <FontIcon Glyph="" />+ </MenuFlyoutItem.Icon>+ <MenuFlyoutItem.KeyboardAccelerators>+ <KeyboardAccelerator Key="V" Modifiers="Control" IsEnabled="False"/>+ </MenuFlyoutItem.KeyboardAccelerators>+ </MenuFlyoutItem>+ <MenuFlyoutItem+ Text="{Binding Instance.Common.Delete, Source={StaticResource LanguageManager}}"+ Command="{Binding DeleteCommand}">+ <MenuFlyoutItem.Icon>+ <FontIcon Glyph="" />+ </MenuFlyoutItem.Icon>+ <MenuFlyoutItem.KeyboardAccelerators>+ <KeyboardAccelerator Key="Delete" IsEnabled="False" />+ </MenuFlyoutItem.KeyboardAccelerators>+ </MenuFlyoutItem>+ <MenuFlyoutSeparator/>+ <MenuFlyoutItem+ Text="{Binding Instance.Common.Undo, Source={StaticResource LanguageManager}}"+ Command="{Binding UndoCommand}">+ <MenuFlyoutItem.Icon>+ <FontIcon Glyph="" />+ </MenuFlyoutItem.Icon>+ <MenuFlyoutItem.KeyboardAccelerators>+ <KeyboardAccelerator Key="Z" Modifiers="Control" IsEnabled="False" />+ </MenuFlyoutItem.KeyboardAccelerators>+ </MenuFlyoutItem>+ <MenuFlyoutItem+ Text="{Binding Instance.Common.Redo, Source={StaticResource LanguageManager}}"+ Command="{Binding RedoCommand}">+ <MenuFlyoutItem.Icon>+ <FontIcon Glyph="" />+ </MenuFlyoutItem.Icon>+ <MenuFlyoutItem.KeyboardAccelerators>+ <KeyboardAccelerator Key="Y" Modifiers="Control" IsEnabled="False" />+ </MenuFlyoutItem.KeyboardAccelerators>+ </MenuFlyoutItem>+ <MenuFlyoutSeparator/>+ <MenuFlyoutItem+ Text="{Binding Instance.Common.SelectAll, Source={StaticResource LanguageManager}}"+ Command="{Binding SelectAllCommand}">+ <MenuFlyoutItem.KeyboardAccelerators>+ <KeyboardAccelerator Key="A" Modifiers="Control" IsEnabled="False" />+ </MenuFlyoutItem.KeyboardAccelerators>+ </MenuFlyoutItem>+ </MenuFlyout>+ </Setter.Value>+ </Setter>+ </Style></ResourceDictionary>diff --git a/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/CommandHandlerResult.cs b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/CommandHandlerResult.csnew file mode 100644index 000000000..6e5954804--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/CommandHandlerResult.cs@@ -0,0 +1,27 @@+#nullable enable++namespace DevTools.Common.UI.Controls.TextEditor+{+ public class CommandHandlerResult+ {+ public CommandHandlerResult(bool shouldHandle, bool shouldSwallow)+ {+ ShouldHandle = shouldHandle;+ ShouldSwallow = shouldSwallow;+ }++ /// <summary>+ /// "ShouldHandle == true" means the keyboard command event should be handled after execution+ /// Meaning you should set KeyRoutedEventArgs.Handled to true after execution+ /// All child OnKeyDown event will not be received and should not be triggered if it is true+ /// </summary>+ public bool ShouldHandle { get; }++ /// <summary>+ /// "ShouldSwallow == true" means the keyboard command event should not go to it's children+ /// Meaning you should not call base.OnKeyDown after execution+ /// All parent OnKeyDown event will not be received and should not be triggered if it is true+ /// </summary>+ public bool ShouldSwallow { get; }+ }+}\ No newline at end of filediff --git a/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/ICommandHandler.cs b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/ICommandHandler.csnew file mode 100644index 000000000..ff0aee1b2--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/ICommandHandler.cs@@ -0,0 +1,9 @@+#nullable enable++namespace DevTools.Common.UI.Controls.TextEditor+{+ public interface ICommandHandler<in T>+ {+ CommandHandlerResult Handle(T args);+ }+}\ No newline at end of filediff --git a/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/IKeyboardCommand.cs b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/IKeyboardCommand.csnew file mode 100644index 000000000..5df9f0917--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/IKeyboardCommand.cs@@ -0,0 +1,19 @@+#nullable enable++using Windows.System;++namespace DevTools.Common.UI.Controls.TextEditor+{+ public interface IKeyboardCommand<T>+ {+ bool Hit(bool ctrlDown, bool altDown, bool shiftDown, VirtualKey key);++ bool ShouldExecute(IKeyboardCommand<T>? lastCommand);++ bool ShouldHandleAfterExecution();++ bool ShouldSwallowAfterExecution();++ void Execute(T args);+ }+}\ No newline at end of filediff --git a/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/KeyboardCommand.cs b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/KeyboardCommand.csnew file mode 100644index 000000000..e541804e8--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/KeyboardCommand.cs@@ -0,0 +1,112 @@+#nullable enable++using System;+using System.Collections.Generic;+using Windows.System;++namespace DevTools.Common.UI.Controls.TextEditor+{+ public class KeyboardCommand<T> : IKeyboardCommand<T>+ {+ private static readonly TimeSpan ConsecutiveHitsInterval = TimeSpan.FromMilliseconds(500);++ private readonly bool _ctrl;+ private readonly bool _alt;+ private readonly bool _shift;+ private readonly IList<VirtualKey> _keys;+ private readonly Action<T>? _action;+ private readonly bool _shouldHandle;+ private readonly bool _shouldSwallow;+ private readonly int _requiredHits;+ private int _hits;+ private DateTime _lastHitTimestamp;++ public KeyboardCommand(+ VirtualKey key,+ Action<T>? action,+ bool shouldHandle = true,+ bool shouldSwallow = true) :+ this(false, false, false, key, action, shouldHandle, shouldSwallow)+ {+ }++ public KeyboardCommand(+ bool ctrlDown,+ bool altDown,+ bool shiftDown,+ VirtualKey key,+ Action<T>? action,+ bool shouldHandle = true,+ bool shouldSwallow = true,+ int requiredHits = 1) :+ this(ctrlDown, altDown, shiftDown, new List<VirtualKey>() { key }, action, shouldHandle, shouldSwallow, requiredHits)+ {+ }++ public KeyboardCommand(+ bool ctrlDown,+ bool altDown,+ bool shiftDown,+ IList<VirtualKey> keys,+ Action<T>? action,+ bool shouldHandle,+ bool shouldSwallow,+ int requiredHits = 1)+ {+ _ctrl = ctrlDown;+ _alt = altDown;+ _shift = shiftDown;+ _keys = keys ?? new List<VirtualKey>();+ _action = action;+ _shouldHandle = shouldHandle;+ _shouldSwallow = shouldSwallow;+ _requiredHits = requiredHits;+ _hits = 0;+ _lastHitTimestamp = DateTime.MinValue;+ }++ public bool Hit(bool ctrlDown, bool altDown, bool shiftDown, VirtualKey key)+ {+ return _ctrl == ctrlDown && _alt == altDown && _shift == shiftDown && _keys.Contains(key);+ }++ public bool ShouldExecute(IKeyboardCommand<T>? lastCommand)+ {+ DateTime now = DateTime.UtcNow;++ if (lastCommand == this && now - _lastHitTimestamp < ConsecutiveHitsInterval)+ {+ _hits++;+ }+ else+ {+ _hits = 1;+ }++ _lastHitTimestamp = now;++ if (_hits >= _requiredHits)+ {+ _hits = 0;+ return true;+ }++ return false;+ }++ public bool ShouldHandleAfterExecution()+ {+ return _shouldHandle;+ }++ public bool ShouldSwallowAfterExecution()+ {+ return _shouldSwallow;+ }++ public void Execute(T args)+ {+ _action?.Invoke(args);+ }+ }+}\ No newline at end of filediff --git a/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/KeyboardCommandHandler.cs b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/KeyboardCommandHandler.csnew file mode 100644index 000000000..28a9a03d4--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/KeyboardCommandHandler.cs@@ -0,0 +1,62 @@+#nullable enable++using System.Collections.Generic;+using Windows.System;+using Windows.UI.Core;+using Windows.UI.Xaml;+using Windows.UI.Xaml.Input;++namespace DevTools.Common.UI.Controls.TextEditor+{+ public class KeyboardCommandHandler : ICommandHandler<KeyRoutedEventArgs>+ {+ public readonly ICollection<IKeyboardCommand<KeyRoutedEventArgs>> Commands;++ private IKeyboardCommand<KeyRoutedEventArgs>? _lastCommand;++ public KeyboardCommandHandler(ICollection<IKeyboardCommand<KeyRoutedEventArgs>> commands)+ {+ Commands = commands;+ }++ public CommandHandlerResult Handle(KeyRoutedEventArgs args)+ {+ var ctrlDown = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down);+ var altDown = Window.Current.CoreWindow.GetKeyState(VirtualKey.Menu).HasFlag(CoreVirtualKeyStates.Down);+ var shiftDown = Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);+ var shouldHandle = false;+ var shouldSwallow = false;++ foreach (var command in Commands)+ {+ if (command.Hit(ctrlDown, altDown, shiftDown, args.Key))+ {+ if (command.ShouldExecute(_lastCommand))+ {+ command.Execute(args);+ }++ if (command.ShouldSwallowAfterExecution())+ {+ shouldSwallow = true;+ }++ if (command.ShouldHandleAfterExecution())+ {+ shouldHandle = true;+ }++ _lastCommand = command;+ break;+ }+ }++ if (!shouldHandle)+ {+ _lastCommand = null;+ }++ return new CommandHandlerResult(shouldHandle, shouldSwallow);+ }+ }+}\ No newline at end of filediff --git a/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/TextEditor.cs b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/TextEditor.csnew file mode 100644index 000000000..256f4d731--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/TextEditor.cs@@ -0,0 +1,1052 @@+#nullable enable++using DevTools.Common.UI.Extensions;+using DevTools.Core;+using DevTools.Core.Settings;+using DevTools.Core.Threading;+using Microsoft.Toolkit.Mvvm.Input;+using System;+using System.Collections.Generic;+using System.Threading;+using System.Threading.Tasks;+using Windows.ApplicationModel.DataTransfer;+using Windows.Foundation;+using Windows.System;+using Windows.UI.Text;+using Windows.UI.Xaml;+using Windows.UI.Xaml.Controls;+using Windows.UI.Xaml.Controls.Primitives;+using Windows.UI.Xaml.Input;+using Windows.UI.Xaml.Media;++namespace DevTools.Common.UI.Controls.TextEditor+{+ [TemplatePart(Name = ContentElementName, Type = typeof(ScrollViewer))]+ [TemplatePart(Name = RootGridName, Type = typeof(Grid))]+ [TemplatePart(Name = LineNumberCanvasName, Type = typeof(Canvas))]+ [TemplatePart(Name = LineNumberGridName, Type = typeof(Grid))]+ [TemplatePart(Name = LineHighlighterAndIndicatorCanvasName, Type = typeof(Canvas))]+ [TemplatePart(Name = LineHighlighterName, Type = typeof(Grid))]+ [TemplatePart(Name = LineIndicatorName, Type = typeof(Border))]+ public sealed class TextEditor : RichEditBox+ {+ private const string ContentElementName = "ContentElement";+ private const string RootGridName = "RootGrid";+ private const string LineNumberCanvasName = "LineNumberCanvas";+ private const string LineNumberGridName = "LineNumberGrid";+ private const string ContentScrollViewerVerticalScrollBarName = "VerticalScrollBar";+ private const string LineHighlighterAndIndicatorCanvasName = "LineHighlighterAndIndicatorCanvas";+ private const string LineHighlighterName = "LineHighlighter";+ private const string LineIndicatorName = "LineIndicator";++ private const string RichEditBoxDefaultLineEnding = "\r\n";++ private readonly IList<TextBlock> _renderedLineNumberBlocks = new List<TextBlock>();+ private readonly Dictionary<string, double> _miniRequisiteIntegerTextRenderingWidthCache = new();+ private readonly SolidColorBrush _lineNumberDarkModeForegroundBrush = new("#99EEEEEE".ToColor());+ private readonly SolidColorBrush _lineNumberLightModeForegroundBrush = new("#99000000".ToColor());+ private readonly ICommandHandler<KeyRoutedEventArgs> _keyboardCommandHandler;++ private CancellationTokenSource _formattingCancellationTokenSource = new CancellationTokenSource();+ private Border? _lineIndicator;+ private Canvas? _lineHighlighterAndIndicatorCanvas;+ private Canvas? _lineNumberCanvas;+ private Grid? _lineHighlighter;+ private Grid? _lineNumberGrid;+ private Grid? _rootGrid;+ private ScrollBar? _contentScrollViewerVerticalScrollBar;+ private ScrollViewer? _contentScrollViewer;+ private bool _showLineNumbers;+ private bool _highlightCurrentLine;+ private bool _loaded;+ private bool _isDocumentLinesCachePendingUpdate = true;+ private bool _isSyntaxColorizationPendingUpdate = true;+ private bool _isSyntaxColorizationUpdateInProgress;+ private string[] _documentLinesCache = Array.Empty<string>(); // internal copy of the active document text in array format+ private string _document = string.Empty; // internal copy of the active document text+ private int _textSelectionStartPosition = 0;+ private int _textSelectionEndPosition = 0;++ public static readonly DependencyProperty SettingsProviderProperty+ = DependencyProperty.Register(+ nameof(SettingsProvider),+ typeof(ISettingsProvider),+ typeof(TextEditor),+ new PropertyMetadata(null, OnSettingsProviderPropertyChangedCallback));++ public ISettingsProvider? SettingsProvider+ {+ get => (ISettingsProvider?)GetValue(SettingsProviderProperty);+ set => SetValue(SettingsProviderProperty, value);+ }++ public static readonly DependencyProperty TextProperty+ = DependencyProperty.Register(+ nameof(Text),+ typeof(string),+ typeof(TextEditor),+ new PropertyMetadata(null, OnTextPropertyChangedCallback));++ public string? Text+ {+ get => (string?)GetValue(TextProperty);+ set => SetValue(TextProperty, value);+ }++ public TextEditor()+ {+ DefaultStyleKey = typeof(TextEditor);++ DataContext = this;+ IsSpellCheckEnabled = false;+ SelectionFlyout = null;+ HorizontalAlignment = HorizontalAlignment.Stretch;+ VerticalAlignment = VerticalAlignment.Stretch;+ HandwritingView.BorderThickness = new Thickness(0);++ Loaded += OnLoaded;+ SelectionChanged += OnSelectionChanged;+ SizeChanged += OnSizeChanged;+ TextChanged += OnTextChanged;+ TextChanging += OnTextChanging;+ SelectionChanging += OnSelectionChanging;+ Paste += OnPaste;++ CutCommand = new RelayCommand(ExecuteCutCommand, CanExecuteCutCommand);+ CopyCommand = new RelayCommand(ExecuteCopyCommand, CanExecuteCopyCommand);+ PasteCommand = new AsyncRelayCommand(ExecutePasteCommandAsync, CanExecutePasteCommand);+ DeleteCommand = new RelayCommand(ExecuteDeleteCommand, CanExecuteDeleteCommand);+ UndoCommand = new RelayCommand(ExecuteUndoCommand, CanExecuteUndoCommand);+ RedoCommand = new RelayCommand(ExecuteRedoCommand, CanExecuteRedoCommand);+ SelectAllCommand = new RelayCommand(ExecuteSelectAllCommand, CanExecuteSelectAllCommand);++ var swallowedKeys = new List<VirtualKey>()+ {+ VirtualKey.B, VirtualKey.I, VirtualKey.U, VirtualKey.Tab,+ VirtualKey.Number1, VirtualKey.Number2, VirtualKey.Number3,+ VirtualKey.Number4, VirtualKey.Number5, VirtualKey.Number6,+ VirtualKey.Number7, VirtualKey.Number8, VirtualKey.Number9,+ VirtualKey.F3,+ };++ _keyboardCommandHandler+ = new KeyboardCommandHandler(new List<IKeyboardCommand<KeyRoutedEventArgs>>+ {+ // By default, RichEditBox insert '\v' when user hit "Shift + Enter"+ // This should be converted to '\r' to match same behaviour as single "Enter"+ new KeyboardCommand<KeyRoutedEventArgs>(false, false, true, VirtualKey.Enter, (args) => EnterWithAutoIndentation()),+ new KeyboardCommand<KeyRoutedEventArgs>(VirtualKey.Enter, (args) => EnterWithAutoIndentation()),+ // Disable RichEditBox default shortcuts (Bold, Underline, Italic)+ // https://docs.microsoft.com/en-us/windows/desktop/controls/about-rich-edit-controls+ new KeyboardCommand<KeyRoutedEventArgs>(true, false, false, swallowedKeys, null, shouldHandle: false, shouldSwallow: true),+ new KeyboardCommand<KeyRoutedEventArgs>(true, false, true, swallowedKeys, null, shouldHandle: false, shouldSwallow: true),+ new KeyboardCommand<KeyRoutedEventArgs>(true, false, true, (VirtualKey)187, null, shouldHandle: false, shouldSwallow: true), // (VirtualKey)187: =+ new KeyboardCommand<KeyRoutedEventArgs>(true, false, true, VirtualKey.L, null, shouldHandle: false, shouldSwallow: true),+ new KeyboardCommand<KeyRoutedEventArgs>(false, false, true, VirtualKey.F3, null, shouldHandle: false, shouldSwallow: true),+ });+ }++ #region CutCommand++ public static readonly DependencyProperty CutCommandProperty+ = DependencyProperty.Register(+ nameof(CutCommand),+ typeof(IRelayCommand),+ typeof(TextEditor),+ new PropertyMetadata(null));++ public IRelayCommand CutCommand+ {+ get => (IRelayCommand)GetValue(CutCommandProperty);+ private set => SetValue(CutCommandProperty, value);+ }++ private bool CanExecuteCutCommand()+ {+ return Document.Selection.Length != 0 && IsEnabled && Document.CanCopy();+ }++ private void ExecuteCutCommand()+ {+ Document.Selection.Cut();+ }++ #endregion++ #region CopyCommand++ public static readonly DependencyProperty CopyCommandProperty+ = DependencyProperty.Register(+ nameof(CopyCommand),+ typeof(IRelayCommand),+ typeof(TextEditor),+ new PropertyMetadata(null));++ public IRelayCommand CopyCommand+ {+ get => (IRelayCommand)GetValue(CopyCommandProperty);+ private set => SetValue(CopyCommandProperty, value);+ }++ private bool CanExecuteCopyCommand()+ {+ return Document.Selection.Length != 0 && IsEnabled && Document.CanCopy();+ }++ private void ExecuteCopyCommand()+ {+ Document.Selection.Copy();+ }++ #endregion++ #region PasteCommand++ public static readonly DependencyProperty PasteCommandProperty+ = DependencyProperty.Register(+ nameof(PasteCommand),+ typeof(IAsyncRelayCommand),+ typeof(TextEditor),+ new PropertyMetadata(null));++ public IAsyncRelayCommand PasteCommand+ {+ get => (IAsyncRelayCommand)GetValue(PasteCommandProperty);+ private set => SetValue(PasteCommandProperty, value);+ }++ private bool CanExecutePasteCommand()+ {+ return Document.CanPaste() && IsEnabled;+ }++ private async Task ExecutePasteCommandAsync()+ {+ await PastePlainTextFromWindowsClipboardAsync(null);+ }++ #endregion++ #region DeleteCommand++ public static readonly DependencyProperty DeleteCommandProperty+ = DependencyProperty.Register(+ nameof(DeleteCommand),+ typeof(IRelayCommand),+ typeof(TextEditor),+ new PropertyMetadata(null));++ public IRelayCommand DeleteCommand+ {+ get => (IRelayCommand)GetValue(DeleteCommandProperty);+ private set => SetValue(DeleteCommandProperty, value);+ }++ private bool CanExecuteDeleteCommand()+ {+ return Document.Selection.Length != 0 && IsEnabled && !IsReadOnly;+ }++ private void ExecuteDeleteCommand()+ {+ Document.BeginUndoGroup();+ Document.Selection.SetText(TextSetOptions.None, string.Empty);+ Document.EndUndoGroup();+ }++ #endregion++ #region UndoCommand++ public static readonly DependencyProperty UndoCommandProperty+ = DependencyProperty.Register(+ nameof(UndoCommand),+ typeof(IRelayCommand),+ typeof(TextEditor),+ new PropertyMetadata(null));++ public IRelayCommand UndoCommand+ {+ get => (IRelayCommand)GetValue(UndoCommandProperty);+ private set => SetValue(UndoCommandProperty, value);+ }++ private bool CanExecuteUndoCommand()+ {+ return Document.CanUndo() && IsEnabled && !IsReadOnly;+ }++ private void ExecuteUndoCommand()+ {+ Document.Undo();+ }++ #endregion++ #region RedoCommand++ public static readonly DependencyProperty RedoCommandProperty+ = DependencyProperty.Register(+ nameof(RedoCommand),+ typeof(IRelayCommand),+ typeof(TextEditor),+ new PropertyMetadata(null));++ public IRelayCommand RedoCommand+ {+ get => (IRelayCommand)GetValue(RedoCommandProperty);+ private set => SetValue(RedoCommandProperty, value);+ }++ private bool CanExecuteRedoCommand()+ {+ return Document.CanRedo() && IsEnabled && !IsReadOnly;+ }++ private void ExecuteRedoCommand()+ {+ Document.Redo();+ }++ #endregion++ #region SelectAllCommand++ public static readonly DependencyProperty SelectAllCommandProperty+ = DependencyProperty.Register(+ nameof(SelectAllCommand),+ typeof(IRelayCommand),+ typeof(TextEditor),+ new PropertyMetadata(null));++ public IRelayCommand SelectAllCommand+ {+ get => (IRelayCommand)GetValue(SelectAllCommandProperty);+ private set => SetValue(SelectAllCommandProperty, value);+ }++ private bool CanExecuteSelectAllCommand()+ {+ return IsEnabled;+ }++ private void ExecuteSelectAllCommand()+ {+ Document.Selection.SetRange(0, int.MaxValue);+ }++ #endregion++ protected override void OnApplyTemplate()+ {+ base.OnApplyTemplate();++ _rootGrid = (Grid)GetTemplateChild(RootGridName);++ _lineNumberGrid = (Grid)GetTemplateChild(LineNumberGridName);+ _lineNumberCanvas = (Canvas)GetTemplateChild(LineNumberCanvasName);++ _lineHighlighterAndIndicatorCanvas = (Canvas)GetTemplateChild(LineHighlighterAndIndicatorCanvasName);+ _lineHighlighter = (Grid)GetTemplateChild(LineHighlighterName);+ _lineIndicator = (Border)GetTemplateChild(LineIndicatorName);++ _contentScrollViewer = (ScrollViewer)GetTemplateChild(ContentElementName);+ _contentScrollViewer.ViewChanged += OnContentScrollViewerViewChanged;+ _contentScrollViewer.SizeChanged += OnContentScrollViewerSizeChanged;++ _contentScrollViewer.ApplyTemplate();+ var scrollViewerRoot = (FrameworkElement)VisualTreeHelper.GetChild(_contentScrollViewer, 0);+ _contentScrollViewerVerticalScrollBar = (ScrollBar)scrollViewerRoot.FindName(ContentScrollViewerVerticalScrollBarName);+ _contentScrollViewerVerticalScrollBar.ValueChanged += OnVerticalScrollBarValueChanged;++ _lineNumberGrid.SizeChanged += OnLineNumberGridSizeChanged;+ _rootGrid.SizeChanged += OnRootGridSizeChanged;+ }++ protected override void OnKeyDown(KeyRoutedEventArgs e)+ {+ var result = _keyboardCommandHandler.Handle(e);++ if (result.ShouldHandle)+ {+ e.Handled = true;+ }++ if (!result.ShouldSwallow)+ {+ base.OnKeyDown(e);+ }+ }++ private void ApplySettings()+ {+ ISettingsProvider? settingsProvider = SettingsProvider;+ if (settingsProvider is not null)+ {+ FontFamily = (FontFamily)Application.Current.Resources[settingsProvider.GetSetting(PredefinedSettings.TextEditorFont)];+ TextWrapping = settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping) ? TextWrapping.Wrap : TextWrapping.NoWrap;+ _showLineNumbers = settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers);+ _highlightCurrentLine = settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine);++ SetDefaultTabStopAndLineSpacing(FontFamily, FontSize);++ UpdateLayout();++ if (_showLineNumbers)+ {+ ShowLineNumbers();+ }+ else+ {+ HideLineNumbers();+ }++ UpdateSyntaxColorization(cancelOnGoingFormattingTask: false);+ }+ }++ private void SetDefaultTabStopAndLineSpacing(FontFamily font, double fontSize)+ {+ Document.DefaultTabStop = (float)GetTextSize(font, fontSize, "text").Width;+ ITextParagraphFormat format = Document.GetDefaultParagraphFormat();+ format.SetLineSpacing(LineSpacingRule.Exactly, (float)fontSize);+ Document.SetDefaultParagraphFormat(format);+ }++ private void ResetRootGridClipping()+ {+ if (!_loaded || _rootGrid is null)+ {+ return;+ }++ _rootGrid!.Clip = new RectangleGeometry+ {+ Rect = new Rect(+ 0,+ 0,+ _rootGrid.ActualWidth,+ Math.Clamp(_rootGrid.ActualHeight, .0f, double.PositiveInfinity))+ };+ }++ private void ShowLineNumbers()+ {+ if (!_loaded)+ {+ return;+ }++ ResetLineNumberCanvasClipping();+ UpdateLineNumbersRendering();++ // Call UpdateLineHighlighterAndIndicator to adjust it's state+ UpdateLineHighlighterAndIndicator();+ }++ private void HideLineNumbers()+ {+ if (!_loaded)+ {+ return;+ }++ Assumes.NotNull(_lineNumberGrid, nameof(_lineNumberGrid));++ foreach (var lineNumberBlock in _renderedLineNumberBlocks)+ {+ lineNumberBlock.Visibility = Visibility.Collapsed;+ }++ _lineNumberGrid!.BorderThickness = new Thickness(0, 0, 0, 0);+ _lineNumberGrid.Margin = new Thickness(0, 0, 0, 0);+ _lineNumberGrid.Width = .0f;++ // Call UpdateLineHighlighterAndIndicator to adjust it's state+ // Since when line highlighter is disabled, we still show the line indicator when line numbers are showing+ UpdateLineHighlighterAndIndicator();+ }++ private void UpdateLineNumbersRendering()+ {+ if (!_loaded || !_showLineNumbers)+ {+ return;+ }++ Assumes.NotNull(_contentScrollViewer, nameof(_contentScrollViewer));++ ITextRange? startRange+ = Document.GetRangeFromPoint(+ new Point(+ _contentScrollViewer!.HorizontalOffset,+ _contentScrollViewer.VerticalOffset),+ PointOptions.ClientCoordinates);++ ITextRange? endRange+ = Document.GetRangeFromPoint(+ new Point(+ _contentScrollViewer.HorizontalOffset + _contentScrollViewer.ViewportWidth,+ _contentScrollViewer.VerticalOffset + _contentScrollViewer.ViewportHeight),+ PointOptions.ClientCoordinates);++ string[]? document = GetDocumentLinesCache();++ Dictionary<int, Rect> lineNumberTextRenderingPositions = CalculateLineNumberTextRenderingPositions(document, startRange, endRange);++ double minLineNumberTextRenderingWidth+ = CalculateMinimumRequisiteIntegerTextRenderingWidth(+ FontFamily,+ FontSize,+ (document.Length - 1).ToString().Length);++ RenderLineNumbersInternal(lineNumberTextRenderingPositions, minLineNumberTextRenderingWidth);+ }++ private void UpdateSyntaxColorization(bool cancelOnGoingFormattingTask)+ {+ if (!_loaded || (_isSyntaxColorizationUpdateInProgress && !cancelOnGoingFormattingTask))+ {+ return;+ }++ // _formattingCancellationTokenSource.Cancel();+ // _formattingCancellationTokenSource.Dispose();+ // _formattingCancellationTokenSource = new CancellationTokenSource();++ // Assumes.NotNull(_contentScrollViewer, nameof(_contentScrollViewer));++ _isSyntaxColorizationUpdateInProgress = true;+ _isSyntaxColorizationPendingUpdate = false;++ // ITextRange? startRange+ // = Document.GetRangeFromPoint(+ // new Point(+ // _contentScrollViewer!.HorizontalOffset - 500,+ // _contentScrollViewer.VerticalOffset - 500),+ // PointOptions.ClientCoordinates);++ // ITextRange? endRange+ // = Document.GetRangeFromPoint(+ // new Point(+ // _contentScrollViewer.HorizontalOffset + _contentScrollViewer.ViewportWidth + 500,+ // _contentScrollViewer.VerticalOffset + _contentScrollViewer.ViewportHeight + 500),+ // PointOptions.ClientCoordinates);++ // ITextRange visibleSpan = Document.GetRange(startRange.StartPosition, endRange.EndPosition);++ // ElementTheme theme = RequestedTheme;+ // if (theme == ElementTheme.Default)+ // {+ // if (Window.Current.Content is FrameworkElement frameworkElement)+ // {+ // theme = frameworkElement.RequestedTheme;+ // }+ // }++ // var formatter = new TextFormatter(theme, Document, visibleSpan);+ // formatter.FormatAsync(Languages.CSharp, _formattingCancellationTokenSource.Token)+ // .ContinueWith(_ =>+ // {+ // _isSyntaxColorizationUpdateInProgress = false;+ // });+ }++ private string[] GetDocumentLinesCache()+ {+ if (_isDocumentLinesCachePendingUpdate)+ {+ _documentLinesCache = (GetText() + RichEditBoxDefaultLineEnding).Split(RichEditBoxDefaultLineEnding);+ _isDocumentLinesCachePendingUpdate = false;+ }++ return _documentLinesCache;+ }++ private Dictionary<int, Rect> CalculateLineNumberTextRenderingPositions(string[] lines, ITextRange startRange, ITextRange endRange)+ {+ int offset = 0;+ Dictionary<int, Rect>? lineRects = new(); // 1 - based++ for (int i = 0; i < lines.Length - 1; i++)+ {+ string line = lines[i] ?? string.Empty;++ ITextRange range = Document.GetRange(offset, offset + line.Length);++ // Use "offset + line.Length + 1" instead of just "offset" here is to capture the line right above the viewport+ if (offset + line.Length + 1 >= startRange.StartPosition && offset <= endRange.EndPosition)+ {+ range.GetRect(PointOptions.ClientCoordinates, out Rect rect, out _);++ lineRects[i + 1] = rect;+ }+ else if (offset > endRange.EndPosition)+ {+ break;+ }++ if (range.Length == 0 && range.Character == '\v')+ {+ offset++;+ }++ offset += line.Length + 1; // 1 for line ending: 'RichEditBoxDefaultLineEnding'+ }++ return lineRects;+ }++ /// <summary>+ /// Get minimum rendering width needed for displaying number text with certain length.+ /// Take length of 3 as example, it is going to iterate thru all possible combinations like:+ /// 111, 222, 333, 444 ... 999 to get minimum rendering length needed to display all of them (the largest width is the min here).+ /// For mono font text, the width is always the same for same length but for non-mono font text, it depends.+ /// Thus we need to calculate here to determine width needed for rendering integer number only text.+ /// </summary>+ /// <param name="fontFamily"></param>+ /// <param name="fontSize"></param>+ /// <param name="numberTextLength"></param>+ /// <returns></returns>+ private double CalculateMinimumRequisiteIntegerTextRenderingWidth(FontFamily fontFamily, double fontSize, int numberTextLength)+ {+ string? cacheKey = $"{fontFamily.Source}-{(int)fontSize}-{numberTextLength}";++ if (_miniRequisiteIntegerTextRenderingWidthCache.ContainsKey(cacheKey))+ {+ return _miniRequisiteIntegerTextRenderingWidthCache[cacheKey];+ }++ double minRequisiteWidth = 0;++ for (int i = 0; i < 10; i++)+ {+ string? str = new((char)('0' + i), numberTextLength);+ double width = GetTextSize(fontFamily, fontSize, str).Width;+ if (width > minRequisiteWidth)+ {+ minRequisiteWidth = width;+ }+ }++ _miniRequisiteIntegerTextRenderingWidthCache[cacheKey] = minRequisiteWidth;+ return minRequisiteWidth;+ }++ private void RenderLineNumbersInternal(Dictionary<int, Rect> lineNumberTextRenderingPositions, double minLineNumberTextRenderingWidth)+ {+ Assumes.NotNull(_lineNumberCanvas, nameof(_lineNumberCanvas));+ Assumes.NotNull(_lineNumberGrid, nameof(_lineNumberGrid));++ double padding = FontSize / 2;+ Thickness lineNumberPadding = new Thickness(padding, 2, padding + 2, 2);+ double lineHeight = GetSingleLineHeight();+ double lineNumberTextBlockHeight = lineHeight + Padding.Top + lineNumberPadding.Top;+ SolidColorBrush? lineNumberForeground = (ActualTheme == ElementTheme.Dark) ? _lineNumberDarkModeForegroundBrush : _lineNumberLightModeForegroundBrush;++ int numOfReusableLineNumberBlocks = _renderedLineNumberBlocks.Count;++ foreach ((int lineNumber, Rect rect) in lineNumberTextRenderingPositions)+ {+ var margin+ = new Thickness(+ lineNumberPadding.Left,+ rect.Top + lineNumberPadding.Top + Padding.Top,+ lineNumberPadding.Right,+ lineNumberPadding.Bottom);++ // Re-use already rendered line number blocks+ if (numOfReusableLineNumberBlocks > 0)+ {+ int index = numOfReusableLineNumberBlocks - 1;+ _renderedLineNumberBlocks[index].Text = lineNumber.ToString();+ _renderedLineNumberBlocks[index].Margin = margin;+ _renderedLineNumberBlocks[index].Height = lineNumberTextBlockHeight;+ _renderedLineNumberBlocks[index].Width = minLineNumberTextRenderingWidth;+ _renderedLineNumberBlocks[index].Visibility = Visibility.Visible;+ _renderedLineNumberBlocks[index].Foreground = lineNumberForeground;++ numOfReusableLineNumberBlocks--;+ }+ else // Render new line number block when there is nothing to re-use+ {+ var lineNumberBlock = new TextBlock()+ {+ Text = lineNumber.ToString(),+ Height = lineNumberTextBlockHeight,+ Width = minLineNumberTextRenderingWidth,+ Margin = margin,+ TextAlignment = TextAlignment.Right,+ HorizontalAlignment = HorizontalAlignment.Right,+ VerticalAlignment = VerticalAlignment.Bottom,+ HorizontalTextAlignment = TextAlignment.Right,+ Foreground = lineNumberForeground+ };++ _lineNumberCanvas!.Children.Add(lineNumberBlock);+ _renderedLineNumberBlocks.Add(lineNumberBlock);+ }+ }++ // Hide all un-used rendered line number block to avoid rendering collision from happening+ for (int i = 0; i < numOfReusableLineNumberBlocks; i++)+ {+ _renderedLineNumberBlocks[i].Visibility = Visibility.Collapsed;+ }++ _lineNumberGrid!.BorderThickness = new Thickness(0, 0, 0.08 * lineHeight, 0);+ _lineNumberGrid.Width = lineNumberPadding.Left + minLineNumberTextRenderingWidth + lineNumberPadding.Right;+ }++ private void ResetLineNumberCanvasClipping()+ {+ if (!_loaded || !_showLineNumbers)+ {+ return;+ }++ Assumes.NotNull(_lineNumberGrid, nameof(_lineNumberGrid));++ _lineNumberGrid!.Margin = new Thickness(0, 0, (-1 * Padding.Left) + 1, 0);+ _lineNumberGrid.Clip = new RectangleGeometry+ {+ Rect = new Rect(+ 0,+ Padding.Top,+ _lineNumberGrid.ActualWidth,+ Math.Clamp(_lineNumberGrid.ActualHeight - (Padding.Top + Padding.Bottom), .0f, double.PositiveInfinity))+ };+ }++ private void UpdateLineHighlighterAndIndicator()+ {+ if (!_loaded || _lineHighlighter is null || _lineIndicator is null || _rootGrid is null)+ {+ return;+ }++ if (!_showLineNumbers && !_highlightCurrentLine)+ {+ _lineHighlighter!.Visibility = Visibility.Collapsed;+ _lineIndicator!.Visibility = Visibility.Collapsed;+ return;+ }++ Document.Selection.GetRect(PointOptions.ClientCoordinates, out Rect selectionRect, out var _);++ double singleLineHeight = GetSingleLineHeight();+ Thickness thickness = new Thickness(0.08 * singleLineHeight);+ double height = selectionRect.Height;++ // Just to make sure height is a positive number and not smaller than single line height+ if (height < singleLineHeight)+ {+ height = singleLineHeight;+ }++ // Show line highlighter rect when it is enabled when selection is single line only+ if (_highlightCurrentLine && height < singleLineHeight * 1.5f)+ {+ _lineHighlighter!.Height = height;+ _lineHighlighter.Margin = new Thickness(0, selectionRect.Y + Padding.Top, 0, 0);+ _lineHighlighter.Width = Math.Clamp(_rootGrid!.ActualWidth, 0, double.PositiveInfinity);++ _lineHighlighter.Visibility = Visibility.Visible;+ }+ else+ {+ _lineHighlighter!.Visibility = Visibility.Collapsed;+ }++ // Show line indicator when line numbers are enabled and when selection is single line only+ if (_showLineNumbers && height < singleLineHeight * 1.5f)+ {+ _lineIndicator!.Height = height;+ _lineIndicator.Margin = new Thickness(0, selectionRect.Y + Padding.Top, 0, 0);+ _lineIndicator.BorderThickness = thickness;+ _lineIndicator.Width = 0.1 * singleLineHeight;++ _lineIndicator.Visibility = Visibility.Visible;+ }+ else+ {+ _lineIndicator!.Visibility = Visibility.Collapsed;+ }+ }++ /// <summary>+ /// Thread safe way of getting the text in the active story (document)+ /// </summary>+ private string GetText()+ {+ return _document;+ }++ private double GetSingleLineHeight()+ {+ Document.GetRange(0, 0).GetRect(PointOptions.ClientCoordinates, out Rect rect, out _);+ return rect.Height <= 0 ? 1.35 * FontSize : rect.Height;+ }++ private void EnterWithAutoIndentation()+ {+ // Automatically indent on new lines based on current line's leading spaces/tabs+ GetLineColumnSelection(out var startLineIndex, out _, out var startColumnIndex, out _, out _, out _);+ var lines = GetDocumentLinesCache();+ var leadingSpacesAndTabs = LeadingSpacesAndTabs(lines[startLineIndex - 1].Substring(0, startColumnIndex - 1));+ Document.Selection.SetText(TextSetOptions.None, RichEditBoxDefaultLineEnding + leadingSpacesAndTabs);+ Document.Selection.StartPosition = Document.Selection.EndPosition;+ }++ /// <summary>+ /// Returns 1-based indexing values+ /// </summary>+ private void GetLineColumnSelection(+ out int startLineIndex,+ out int endLineIndex,+ out int startColumnIndex,+ out int endColumnIndex,+ out int selectedCount,+ out int lineCount)+ {+ var lines = GetDocumentLinesCache();+ GetTextSelectionPosition(out var start, out var end);++ startLineIndex = 1;+ startColumnIndex = 1;+ endLineIndex = 1;+ endColumnIndex = 1;+ selectedCount = 0;+ lineCount = lines.Length - 1;++ var length = 0;+ bool startLocated = false;++ for (int i = 0; i < lineCount + 1; i++)+ {+ var line = lines[i];++ if (line.Length + length >= start && !startLocated)+ {+ startLineIndex = i + 1;+ startColumnIndex = start - length + 1;+ startLocated = true;+ }++ if (line.Length + length >= end)+ {+ if (i == startLineIndex - 1)+ {+ selectedCount = end - start;+ }+ else+ {+ selectedCount = end - start + (i - startLineIndex) + 1;+ }++ endLineIndex = i + 1;+ endColumnIndex = end - length + 1;++ // Reposition end position to previous line's end position if last selected char is RichEditBoxDefaultLineEnding ('\r')+ if (endColumnIndex == 1 && end != start)+ {+ endLineIndex--;+ endColumnIndex = lines[i - 1].Length + 1;+ }++ return;+ }++ length += line.Length + 1;+ }+ }++ /// <summary>+ /// Thread safe way of getting the current document selection position+ /// </summary>+ private void GetTextSelectionPosition(out int startPosition, out int endPosition)+ {+ startPosition = _textSelectionStartPosition;+ endPosition = _textSelectionEndPosition;+ }++ private async Task PastePlainTextFromWindowsClipboardAsync(TextControlPasteEventArgs? args)+ {+ if (args != null)+ {+ args.Handled = true;+ }++ if (!Document.CanPaste())+ {+ return;+ }++ try+ {+ DataPackageView? dataPackageView = Clipboard.GetContent();+ if (!dataPackageView.Contains(StandardDataFormats.Text))+ {+ return;+ }++ string? text = await dataPackageView.GetTextAsync();++ Document.BeginUndoGroup();+ Document.Selection.SetText(TextSetOptions.None, text);+ Document.Selection.StartPosition = Document.Selection.EndPosition;+ Document.EndUndoGroup();+ }+ catch (Exception ex)+ {+ // TODO: Log this.+ }+ }++ private void SettingProvider_SettingChanged(object sender, SettingChangedEventArgs e)+ {+ ApplySettings();+ }++ private void OnContentScrollViewerViewChanged(object sender, ScrollViewerViewChangedEventArgs _)+ {+ UpdateLineNumbersRendering();+ UpdateSyntaxColorization(cancelOnGoingFormattingTask: false);+ }++ private void OnContentScrollViewerSizeChanged(object sender, SizeChangedEventArgs _)+ {+ UpdateLineNumbersRendering();+ UpdateSyntaxColorization(cancelOnGoingFormattingTask: false);+ }++ private void OnVerticalScrollBarValueChanged(object sender, RangeBaseValueChangedEventArgs _)+ {+ Assumes.NotNull(_contentScrollViewer, nameof(_contentScrollViewer));+ Assumes.NotNull(_lineNumberCanvas, nameof(_lineNumberCanvas));+ Assumes.NotNull(_lineHighlighterAndIndicatorCanvas, nameof(_lineHighlighterAndIndicatorCanvas));++ // Make sure line number canvas is in sync with editor's ScrollViewer+ _contentScrollViewer!.StartExpressionAnimation(_lineNumberCanvas!, Axis.Y);++ // Make sure line highlighter and indicator canvas is in sync with editor's ScrollViewer+ _contentScrollViewer!.StartExpressionAnimation(_lineHighlighterAndIndicatorCanvas!, Axis.Y);+ }++ private void OnLineNumberGridSizeChanged(object sender, SizeChangedEventArgs e)+ {+ ResetLineNumberCanvasClipping();+ }++ private void OnRootGridSizeChanged(object sender, SizeChangedEventArgs _)+ {+ ResetRootGridClipping();+ }++ private void OnPaste(object sender, TextControlPasteEventArgs e)+ {+ PastePlainTextFromWindowsClipboardAsync(e).Forget();+ }++ private void OnLoaded(object sender, RoutedEventArgs e)+ {+ _loaded = true;++ ResetRootGridClipping();++ UpdateLineHighlighterAndIndicator();+ if (_showLineNumbers)+ {+ ShowLineNumbers();+ }++ UpdateSyntaxColorization(cancelOnGoingFormattingTask: false);+ }++ private void OnSelectionChanging(RichEditBox sender, RichEditBoxSelectionChangingEventArgs args)+ {+ _textSelectionStartPosition = args.SelectionStart;+ _textSelectionEndPosition = args.SelectionStart + args.SelectionLength;+ }++ private void OnSelectionChanged(object sender, RoutedEventArgs _)+ {+ UpdateLineHighlighterAndIndicator();+ }++ private void OnSizeChanged(object sender, SizeChangedEventArgs _)+ {+ UpdateLineHighlighterAndIndicator();+ }++ private void OnTextChanging(RichEditBox sender, RichEditBoxTextChangingEventArgs args)+ {+ if (args.IsContentChanging)+ {+ Document.GetText(TextGetOptions.UseCrlf, out var document);+ _document = document;++ _isDocumentLinesCachePendingUpdate = true;+ _isSyntaxColorizationPendingUpdate = true;+ }+ }++ private void OnTextChanged(object sender, RoutedEventArgs _)+ {+ UpdateLineNumbersRendering();++ if (_isSyntaxColorizationPendingUpdate)+ {+ UpdateSyntaxColorization(cancelOnGoingFormattingTask: true);+ }+ }++ private static void OnSettingsProviderPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)+ {+ ISettingsProvider? settingProvider = e.NewValue as ISettingsProvider;+ if (settingProvider is not null)+ {+ var textEditorCore = (TextEditor)d;+ settingProvider.SettingChanged += textEditorCore.SettingProvider_SettingChanged;+ textEditorCore.ApplySettings();+ }+ }++ private static void OnTextPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)+ {+ string? text = e.NewValue as string;+ var textEditorCore = (TextEditor)d;++ bool isReadOnly = textEditorCore.IsReadOnly;+ textEditorCore.IsReadOnly = false;+ textEditorCore.Document.SetText(TextSetOptions.None, text);+ textEditorCore.IsReadOnly = isReadOnly;+ }++ private static Size GetTextSize(FontFamily font, double fontSize, string text)+ {+ var textBlock = new TextBlock+ {+ Text = text,+ FontFamily = font,+ FontSize = fontSize+ };+ textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));+ return textBlock.DesiredSize;+ }++ private static string LeadingSpacesAndTabs(string str)+ {+ int i = 0;+ for (; i < str.Length; i++)+ {+ var ch = str[i];+ if (ch != ' ' && ch != '\t')+ {+ break;+ }+ }+ return str.Substring(0, i);+ }+ }+}diff --git a/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/TextFormatter.cs b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/TextFormatter.csnew file mode 100644index 000000000..cde14b80c--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Controls/TextEditor/TextFormatter.cs@@ -0,0 +1,205 @@+#nullable enable++using ColorCode;+using ColorCode.Common;+using ColorCode.Parsing;+using ColorCode.Styling;+using DevTools.Common.UI.Extensions;+using DevTools.Core.Threading;+using System;+using System.Collections.Generic;+using System.Linq;+using System.Threading;+using System.Threading.Tasks;+using Windows.ApplicationModel.Core;+using Windows.UI;+using Windows.UI.Text;+using Windows.UI.Xaml;++namespace DevTools.Common.UI.Controls.TextEditor+{+ /// <summary>+ /// Creates a <see cref="TextFormatter"/>, for rendering Syntax Highlighted code to a RichTextBox.+ /// </summary>+ internal sealed class TextFormatter : CodeColorizerBase+ {+ private readonly ITextDocument _textDocument;+ private readonly ITextRange _span;+ private readonly List<(int startPosition, string text, Scope? scope)> _pendingUpdates = new();+ private int _parsedSourceCodePosition;++ /// <summary>+ /// Creates a <see cref="TextFormatter"/>, for rendering Syntax Highlighted code to a RichTextBox.+ /// </summary>+ /// <param name="Theme">The Theme to use, determines whether to use Default Light or Default Dark.</param>+ internal TextFormatter(ElementTheme Theme, ITextDocument textDocument, ITextRange span, ILanguageParser? languageParser = null)+ : base(Theme == ElementTheme.Dark ? StyleDictionary.DefaultDark : StyleDictionary.DefaultLight, languageParser)+ {+ _textDocument = textDocument;+ _span = span;+ }++ /// <summary>+ /// Adds Syntax Highlighted Source Code to the provided RichTextBox.+ /// </summary>+ /// <param name="language">The language to use to colorize the source code.</param>+ /// <param name="textEditor">The Control to add the Text to.</param>+ internal async Task FormatAsync(ILanguage language, CancellationToken cancellationToken)+ {+ await TaskScheduler.Default;++ _span.GetText(TextGetOptions.UseCrlf, out string sourceCode);+ _parsedSourceCodePosition = _span.StartPosition;++ languageParser.Parse(+ sourceCode,+ language,+ (parsedSourceCode, captures) =>+ {+ cancellationToken.ThrowIfCancellationRequested();+ Write(parsedSourceCode, captures);+ });++ cancellationToken.ThrowIfCancellationRequested();++ const int chunkSize = 5;+ int i = 0;++ while (i < _pendingUpdates.Count)+ {+ var items = _pendingUpdates.Skip(i).Take(chunkSize);+ i += chunkSize;++ cancellationToken.ThrowIfCancellationRequested();++ await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(+ Windows.UI.Core.CoreDispatcherPriority.Low,+ () =>+ {+ foreach (var item in items)+ {+ if (cancellationToken.IsCancellationRequested)+ {+ break;+ }++ ApplyStyle(item.startPosition, item.text, item.scope);+ }+ });+ }+ }++ protected override void Write(string parsedSourceCode, IList<Scope> scopes)+ {+ var styleInsertions = new List<TextInsertion>();++ foreach (Scope scope in scopes)+ {+ GetStyleInsertionsForCapturedStyle(scope, styleInsertions);+ }++ styleInsertions.SortStable((x, y) => x.Index.CompareTo(y.Index));++ int parsedSourceCodePosition = _parsedSourceCodePosition;+ int offset = 0;++ Scope? previousScope = null;++ foreach (TextInsertion? styleinsertion in styleInsertions)+ {+ string text = parsedSourceCode.Substring(offset, styleinsertion.Index - offset);+ if (!string.IsNullOrEmpty(text))+ {+ _pendingUpdates.Add(new(parsedSourceCodePosition + offset, text, previousScope));+ }++ if (!string.IsNullOrWhiteSpace(styleinsertion.Text))+ {+ _pendingUpdates.Add(new(parsedSourceCodePosition, text, previousScope));+ }++ offset = styleinsertion.Index;+ previousScope = styleinsertion.Scope;+ }++ string remaining = parsedSourceCode.Substring(offset);++ // Ensures that those loose carriages don't run away!+ if (!string.IsNullOrEmpty(remaining) && remaining != "\r")+ {+ _pendingUpdates.Add(new(parsedSourceCodePosition + offset, remaining, null));+ }++ _parsedSourceCodePosition += parsedSourceCode.Length - CountStringOccurrences(parsedSourceCode, "\r");+ }++ private void ApplyStyle(int startPosition, string text, Scope? scope)+ {+ ITextRange span = _textDocument.GetRange(startPosition, startPosition + text.Length);+ ColorCode.Styling.Style style;++ if (scope is not null && Styles.Contains(scope.Name))+ {+ style = Styles[scope.Name];+ }+ else+ {+ style = Styles["Plain Text"]; // Default+ }++ string? foreground = style.Foreground;+ bool italic = style.Italic;+ bool bold = style.Bold;++ if (!string.IsNullOrWhiteSpace(foreground))+ {+ span.CharacterFormat.ForegroundColor = foreground!.ToColor();+ }++ if (italic)+ {+ span.CharacterFormat.FontStyle = FontStyle.Italic;+ }++ if (bold)+ {+ span.CharacterFormat.Bold = FormatEffect.On;+ }+ }++ private void GetStyleInsertionsForCapturedStyle(Scope scope, ICollection<TextInsertion> styleInsertions)+ {+ styleInsertions.Add(new TextInsertion+ {+ Index = scope.Index,+ Scope = scope+ });++ foreach (Scope childScope in scope.Children)+ {+ GetStyleInsertionsForCapturedStyle(childScope, styleInsertions);+ }++ styleInsertions.Add(new TextInsertion+ {+ Index = scope.Index + scope.Length+ });+ }++ /// <summary>+ /// Count occurrences of strings.+ /// </summary>+ private static int CountStringOccurrences(string text, string pattern)+ {+ // Loop through all instances of the string 'text'.+ int count = 0;+ int i = 0;+ while ((i = text.IndexOf(pattern, i)) != -1)+ {+ i += pattern.Length;+ count++;+ }+ return count;+ }+ }+}diff --git a/src/dev/impl/DevTools.Common/UI/Extensions/Axis.cs b/src/dev/impl/DevTools.Common/UI/Extensions/Axis.csnew file mode 100644index 000000000..0cef2ab7a--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Extensions/Axis.cs@@ -0,0 +1,20 @@+#nullable enable++namespace DevTools.Common.UI.Extensions+{+ /// <summary>+ /// Indicates an axis in the 2D space+ /// </summary>+ internal enum Axis+ {+ /// <summary>+ /// The X axis (horizontal)+ /// </summary>+ X,++ /// <summary>+ /// The Y axis (vertical)+ /// </summary>+ Y+ }+}diff --git a/src/dev/impl/DevTools.Common/UI/Extensions/ColorHelper.cs b/src/dev/impl/DevTools.Common/UI/Extensions/ColorHelper.csnew file mode 100644index 000000000..09a1ba725--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Extensions/ColorHelper.cs@@ -0,0 +1,103 @@+#nullable enable++using DevTools.Core;+using System;+using System.Reflection;+using Windows.UI;++namespace DevTools.Common.UI.Extensions+{+ internal static class ColorHelper+ {+ /// <summary>+ /// Creates a <see cref="Windows.UI.Color"/> from a XAML color <see cref="string"/>. Any format used in XAML should work.+ /// </summary>+ /// <param name="colorString">The XAML color string.</param>+ /// <returns>The created <see cref="Windows.UI.Color"/>.</returns>+ public static Color ToColor(this string colorString)+ {+ Arguments.NotNullOrEmpty(colorString, nameof(colorString));++ if (colorString[0] == '#')+ {+ switch (colorString.Length)+ {+ case 9:+ {+ uint num4 = Convert.ToUInt32(colorString.Substring(1), 16);+ byte a = (byte)(num4 >> 24);+ byte r2 = (byte)((num4 >> 16) & 0xFF);+ byte g2 = (byte)((num4 >> 8) & 0xFF);+ byte b9 = (byte)(num4 & 0xFF);+ return Color.FromArgb(a, r2, g2, b9);+ }+ case 7:+ {+ uint num3 = Convert.ToUInt32(colorString.Substring(1), 16);+ byte r = (byte)((num3 >> 16) & 0xFF);+ byte g = (byte)((num3 >> 8) & 0xFF);+ byte b8 = (byte)(num3 & 0xFF);+ return Color.FromArgb(byte.MaxValue, r, g, b8);+ }+ case 5:+ {+ ushort num2 = Convert.ToUInt16(colorString.Substring(1), 16);+ byte b4 = (byte)(num2 >> 12);+ byte b5 = (byte)((num2 >> 8) & 0xF);+ byte b6 = (byte)((num2 >> 4) & 0xF);+ byte b7 = (byte)(num2 & 0xF);+ b4 = (byte)((b4 << 4) | b4);+ b5 = (byte)((b5 << 4) | b5);+ b6 = (byte)((b6 << 4) | b6);+ b7 = (byte)((b7 << 4) | b7);+ return Color.FromArgb(b4, b5, b6, b7);+ }+ case 4:+ {+ ushort num = Convert.ToUInt16(colorString.Substring(1), 16);+ byte b = (byte)((num >> 8) & 0xF);+ byte b2 = (byte)((num >> 4) & 0xF);+ byte b3 = (byte)(num & 0xF);+ b = (byte)((b << 4) | b);+ b2 = (byte)((b2 << 4) | b2);+ b3 = (byte)((b3 << 4) | b3);+ return Color.FromArgb(byte.MaxValue, b, b2, b3);+ }+ default:+ throw new FormatException($"The {colorString} string passed in the colorString argument is not a recognized Color format.");+ }+ }++ if (colorString.Length > 3 && colorString[0] == 's' && colorString[1] == 'c' && colorString[2] == '#')+ {+ string[] array = colorString.Split(',');+ if (array.Length == 4)+ {+ double num5 = double.Parse(array[0].Substring(3));+ double num6 = double.Parse(array[1]);+ double num7 = double.Parse(array[2]);+ double num8 = double.Parse(array[3]);+ return Color.FromArgb((byte)(num5 * 255.0), (byte)(num6 * 255.0), (byte)(num7 * 255.0), (byte)(num8 * 255.0));+ }++ if (array.Length == 3)+ {+ double num9 = double.Parse(array[0].Substring(3));+ double num10 = double.Parse(array[1]);+ double num11 = double.Parse(array[2]);+ return Color.FromArgb(byte.MaxValue, (byte)(num9 * 255.0), (byte)(num10 * 255.0), (byte)(num11 * 255.0));+ }++ throw new FormatException($"The {colorString} string passed in the colorString argument is not a recognized Color format (sc#[scA,]scR,scG,scB).");+ }++ PropertyInfo declaredProperty = typeof(Colors).GetTypeInfo().GetDeclaredProperty(colorString);+ if (declaredProperty != null)+ {+ return (Color)declaredProperty.GetValue(null);+ }++ throw new FormatException($"The {colorString} string passed in the colorString argument is not a recognized Color.");+ }+ }+}diff --git a/src/dev/impl/DevTools.Common/UI/Extensions/ScrollViewerExtensions.cs b/src/dev/impl/DevTools.Common/UI/Extensions/ScrollViewerExtensions.csnew file mode 100644index 000000000..b321f56dd--- /dev/null+++ b/src/dev/impl/DevTools.Common/UI/Extensions/ScrollViewerExtensions.cs@@ -0,0 +1,37 @@+#nullable enable++using Windows.UI.Composition;+using Windows.UI.Xaml;+using Windows.UI.Xaml.Controls;+using Windows.UI.Xaml.Hosting;++namespace DevTools.Common.UI.Extensions+{+ internal static class ScrollViewerExtensions+ {+ internal static ExpressionAnimation StartExpressionAnimation(+ this ScrollViewer scrollViewer,+ UIElement target,+ Axis axis)+ {+ return scrollViewer.StartExpressionAnimation(target, sourceAxis: axis, targetAxis: axis);+ }++ internal static ExpressionAnimation StartExpressionAnimation(+ this ScrollViewer scrollViewer,+ UIElement target,+ Axis sourceAxis,+ Axis targetAxis)+ {+ CompositionPropertySet scrollSet = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(scrollViewer);++ ExpressionAnimation animation = scrollSet.Compositor.CreateExpressionAnimation($"{nameof(scrollViewer)}.{nameof(UIElement.Translation)}.{sourceAxis}");+ animation.SetReferenceParameter(nameof(scrollViewer), scrollSet);++ Visual visual = ElementCompositionPreview.GetElementVisual(target);+ visual.StartAnimation($"{nameof(Visual.Offset)}.{targetAxis}", animation);++ return animation;+ }+ }+}diff --git a/src/dev/impl/DevTools.Impl/Views/Settings/SettingsToolPage.xaml b/src/dev/impl/DevTools.Impl/Views/Settings/SettingsToolPage.xamlindex ddc403942..808c5ac8f 100644--- a/src/dev/impl/DevTools.Impl/Views/Settings/SettingsToolPage.xaml+++ b/src/dev/impl/DevTools.Impl/Views/Settings/SettingsToolPage.xaml@@ -69,6 +69,29 @@<ComboBoxItem Tag="SegoeUI" FontFamily="{StaticResource SegoeUI}" Content="Segoe UI"/></ComboBox></controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.Strings.WordWrap}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch Style="{StaticResource RightAlignedToggleSwitchStyle}" IsOn="{x:Bind ViewModel.TextEditorTextWrapping, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.Strings.LineNumbers}"+ Description="{x:Bind ViewModel.Strings.LineNumbersDescription}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="ǀ" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch Style="{StaticResource RightAlignedToggleSwitchStyle}" IsOn="{x:Bind ViewModel.TextEditorLineNumbers, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ </controls:ExpandableSettingControl>+ <controls:ExpandableSettingControl+ Title="{x:Bind ViewModel.Strings.HighlightCurrentLine}"+ Description="{x:Bind ViewModel.Strings.HighlightCurrentLineDescription}">+ <controls:ExpandableSettingControl.Icon>+ <FontIcon Glyph="" />+ </controls:ExpandableSettingControl.Icon>+ <ToggleSwitch Style="{StaticResource RightAlignedToggleSwitchStyle}" IsOn="{x:Bind ViewModel.TextEditorHighlightCurrentLine, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>+ </controls:ExpandableSettingControl><TextBlock Style="{StaticResource SubTitleTextBlock}" Text="{x:Bind ViewModel.Strings.About}" />diff --git a/src/dev/impl/DevTools.Impl/Views/Settings/SettingsToolViewModel.cs b/src/dev/impl/DevTools.Impl/Views/Settings/SettingsToolViewModel.csindex 15f99bbd8..0d49ab491 100644--- a/src/dev/impl/DevTools.Impl/Views/Settings/SettingsToolViewModel.cs+++ b/src/dev/impl/DevTools.Impl/Views/Settings/SettingsToolViewModel.cs@@ -37,6 +37,24 @@ namespace DevTools.Impl.Views.Settingsset => _settingsProvider.SetSetting(PredefinedSettings.TextEditorFont, value);}+ internal bool TextEditorTextWrapping+ {+ get => _settingsProvider.GetSetting(PredefinedSettings.TextEditorTextWrapping);+ set => _settingsProvider.SetSetting(PredefinedSettings.TextEditorTextWrapping, value);+ }++ internal bool TextEditorLineNumbers+ {+ get => _settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers);+ set => _settingsProvider.SetSetting(PredefinedSettings.TextEditorLineNumbers, value);+ }++ internal bool TextEditorHighlightCurrentLine+ {+ get => _settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine);+ set => _settingsProvider.SetSetting(PredefinedSettings.TextEditorHighlightCurrentLine, value);+ }+[ImportingConstructor]public SettingsToolViewModel(ISettingsProvider settingsProvider)diff --git a/src/dev/impl/DevTools.Providers.Impl/Tools/JsonFormatter/JsonFormatterToolPage.xaml b/src/dev/impl/DevTools.Providers.Impl/Tools/JsonFormatter/JsonFormatterToolPage.xamlindex 7f0ae3789..bd706901c 100644--- a/src/dev/impl/DevTools.Providers.Impl/Tools/JsonFormatter/JsonFormatterToolPage.xaml+++ b/src/dev/impl/DevTools.Providers.Impl/Tools/JsonFormatter/JsonFormatterToolPage.xaml@@ -5,10 +5,13 @@xmlns:local="using:DevTools.Providers.Impl.Tools.JsonFormatter"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"+ xmlns:texteditor="using:DevTools.Common.UI.Controls.TextEditor"mc:Ignorable="d"NavigationCacheMode="Required">- <Grid>- <TextBlock Text="JsonFormatterToolPage" HorizontalAlignment="Center" VerticalAlignment="Center" />+ <Grid Height="400" HorizontalAlignment="Stretch" VerticalAlignment="Top">+ <texteditor:TextEditor+ SettingsProvider="{x:Bind ViewModel.SettingsProvider}"+ Text="Hello Dummy There"/></Grid></Page>diff --git a/src/dev/impl/DevTools.Providers.Impl/Tools/JsonFormatter/JsonFormatterToolViewModel.cs b/src/dev/impl/DevTools.Providers.Impl/Tools/JsonFormatter/JsonFormatterToolViewModel.csindex 766c3f57e..deb1d8f18 100644--- a/src/dev/impl/DevTools.Providers.Impl/Tools/JsonFormatter/JsonFormatterToolViewModel.cs+++ b/src/dev/impl/DevTools.Providers.Impl/Tools/JsonFormatter/JsonFormatterToolViewModel.cs@@ -1,5 +1,6 @@#nullable enable+using DevTools.Core.Settings;using Microsoft.Toolkit.Mvvm.ComponentModel;using System;using System.Composition;@@ -10,5 +11,13 @@ namespace DevTools.Providers.Impl.Tools.JsonFormatterpublic class JsonFormatterToolViewModel : ObservableRecipient, IToolViewModel{public Type View { get; } = typeof(JsonFormatterToolPage);++ internal ISettingsProvider SettingsProvider { get; }++ [ImportingConstructor]+ public JsonFormatterToolViewModel(ISettingsProvider settingsProvider)+ {+ SettingsProvider = settingsProvider;+ }}}