Skip to content

Commit

Permalink
Add Settings to manage Folding (#78)
Browse files Browse the repository at this point in the history
Add settings to define:

Folding On/Off
Fold root elements On/Off
  • Loading branch information
sachabruttin authored Jun 21, 2022
1 parent 50c6657 commit ed5a83c
Show file tree
Hide file tree
Showing 15 changed files with 186 additions and 31 deletions.
27 changes: 19 additions & 8 deletions src/CosmosDbExplorer.Core/Helpers/FoldFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,20 @@ namespace CosmosDbExplorer.Core.Helpers
/// </summary>
public class FoldFinder
{
private readonly bool _foldableRoot;
private readonly IList<Delimiter> _delimiters;
private readonly Regex _scanner;

public FoldFinder(IList<Delimiter> delimiters, bool foldableRoot = true)
{
_foldableRoot = foldableRoot;
FoldableRoot = foldableRoot;
_delimiters = delimiters;
_scanner = RegexifyDelimiters(delimiters);
}

public int FirstErrorOffset { get; private set; } = -1;

public bool FoldableRoot { get; set; }

public IList<FoldMatch> Scan(string code, int start = 0, int end = -1, bool throwOnError = true)
{
FirstErrorOffset = -1;
Expand All @@ -37,9 +38,9 @@ public IList<FoldMatch> Scan(string code, int start = 0, int end = -1, bool thro
Delimiter matchedDelimiter;
var currentItem = default(FoldStackItem);

foreach (Match match in _scanner.Matches(code, start))
foreach (var match in _scanner.Matches(code, start).Cast<Match>())
{
if (!_foldableRoot && match.Index == 0)
if (!FoldableRoot && match.Index == 0)
{
continue;
}
Expand Down Expand Up @@ -152,22 +153,32 @@ private static Regex RegexifyDelimiters(IList<Delimiter> delimiters)
string.Format("((\\{0})|(\\{1}))", d.Start, d.End))), RegexOptions.Compiled | RegexOptions.Multiline);
}

private class FoldStackItem
private struct FoldStackItem
{
public FoldMatch Position;
public Delimiter Delimter;
}



}

public class FoldMatch
public struct FoldMatch
{
public int Start;
public int End;
}

public class Delimiter
{
public string Start;
public string End;
public Delimiter(string start, string end)
{
Start = start;
End = end;
}

public string Start { get; private set; }
public string End { get; private set; }
}

}
55 changes: 55 additions & 0 deletions src/CosmosDbExplorer/App.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CosmosDbExplorer.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="CosmosDbExplorer.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<CosmosDbExplorer.Properties.Settings>
<setting name="EditorFontName" serializeAs="String">
<value>Consolas</value>
</setting>
<setting name="EditorFontSize" serializeAs="String">
<value>11</value>
</setting>
<setting name="Theme" serializeAs="String">
<value>Default</value>
</setting>
<setting name="ExportFolder" serializeAs="String">
<value />
</setting>
<setting name="MaxDocumentToRetrieve" serializeAs="String">
<value>50</value>
</setting>
<setting name="DialogService" serializeAs="String">
<value>Metro</value>
</setting>
<setting name="ExecuteGesture" serializeAs="String">
<value>F5</value>
</setting>
<setting name="ShowLineNumbers" serializeAs="String">
<value>True</value>
</setting>
<setting name="EnableWordWrap" serializeAs="String">
<value>False</value>
</setting>
<setting name="EnableFolding" serializeAs="String">
<value>True</value>
</setting>
<setting name="FoldingRootElement" serializeAs="String">
<value>True</value>
</setting>
</CosmosDbExplorer.Properties.Settings>
</userSettings>
<applicationSettings>
<CosmosDbExplorer.Properties.Settings>
<setting name="AutoUpdaterUrl" serializeAs="String">
<value>https://www.bruttin.com/CosmosDbExplorer/autoupdate.json</value>
</setting>
</CosmosDbExplorer.Properties.Settings>
</applicationSettings>
</configuration>
13 changes: 8 additions & 5 deletions src/CosmosDbExplorer/AvalonEdit/BraceFoldingStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,25 @@ namespace CosmosDbExplorer.AvalonEdit
public class BraceFoldingStrategy
{
private readonly FoldFinder _foldFinder;

/// <summary>
/// Creates a new BraceFoldingStrategy.
/// </summary>
public BraceFoldingStrategy()
public BraceFoldingStrategy(bool foldRoot)
{
_foldFinder = new FoldFinder(new List<Delimiter> {
//Json Object Delimiters
new Delimiter { Start = "{", End = "}" },
new Delimiter( start: "{", end: "}" ),
//Json Array Delimiters
new Delimiter { Start = "[", End = "]" }
}, false);
new Delimiter( start: "[", end: "]" )
}, foldRoot);
}

public bool FoldRootElement { get => _foldFinder.FoldableRoot; set => _foldFinder.FoldableRoot = value; }

public void UpdateFoldings(FoldingManager manager, TextDocument document)
{
var newFoldings = CreateNewFoldings(document, out int firstErrorOffset);
var newFoldings = CreateNewFoldings(document, out var firstErrorOffset);
manager.UpdateFoldings(newFoldings, firstErrorOffset);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using System.Windows.Threading;
using CosmosDbExplorer.AvalonEdit;
using CosmosDbExplorer.Core.Helpers;
using CosmosDbExplorer.Properties;

using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Folding;
using Microsoft.Xaml.Behaviors;
Expand All @@ -11,16 +13,20 @@ namespace CosmosDbExplorer.Behaviors
{
public class AvalonTextEditorBraceFoldingBehavior : Behavior<TextEditor>
{
private readonly BraceFoldingStrategy _foldingStrategy = new();
private readonly BraceFoldingStrategy _foldingStrategy = new(Settings.Default.FoldingRootElement);
private FoldingManager? _foldingManager;
private readonly TimedDebounce _timer = new() { WaitingMilliSeconds = 500 };

protected override void OnAttached()
{
base.OnAttached();

OnUseFoldingChanged();

_timer.Idled += OnTextChangedIdle;
AssociatedObject.TextChanged += OnTextChanged;
}

protected override void OnDetaching()
{
_timer.Idled -= OnTextChangedIdle;
Expand Down Expand Up @@ -86,11 +92,41 @@ private void OnUseFoldingChanged()
}
}

public bool FoldRootElement
{
get { return (bool)GetValue(FoldRootElementProperty); }
set { SetValue(FoldRootElementProperty, value); }
}

// Using a DependencyProperty as the backing store for FoldRootElement. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FoldRootElementProperty =
DependencyProperty.Register(
"FoldRootElement",
typeof(bool),
typeof(AvalonTextEditorBraceFoldingBehavior),
new PropertyMetadata(true, OnFoldRootElementPropertyChanged));

private static void OnFoldRootElementPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is AvalonTextEditorBraceFoldingBehavior behavior)
{
behavior.OnFoldRootElementChanged();
}
}

private void OnFoldRootElementChanged()
{
_foldingStrategy.FoldRootElement = FoldRootElement;

OnTextChangedIdle(null, new EventArgs());
}

private void InitFoldingManager()
{
if (_foldingManager is null && AssociatedObject?.TextArea is not null)
{
_foldingManager = FoldingManager.Install(AssociatedObject.TextArea);
OnTextChangedIdle(null, new EventArgs());
}
}

Expand Down
26 changes: 25 additions & 1 deletion src/CosmosDbExplorer/Properties/Settings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions src/CosmosDbExplorer/Properties/Settings.settings
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,11 @@
<Setting Name="AutoUpdaterUrl" Type="System.String" Scope="Application">
<Value Profile="(Default)">https://www.bruttin.com/CosmosDbExplorer/autoupdate.json</Value>
</Setting>
<Setting Name="EnableFolding" Type="System.Boolean" Scope="User">
<Value Profile="(Default)">True</Value>
</Setting>
<Setting Name="FoldingRootElement" Type="System.Boolean" Scope="User">
<Value Profile="(Default)">True</Value>
</Setting>
</Settings>
</SettingsFile>
4 changes: 2 additions & 2 deletions src/CosmosDbExplorer/Styles/CosmosDbExplorerThemeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace CosmosDbExplorer.Styles
{
public class CosmosDbExplorerThemeProvider : /*MahAppsLibraryThemeProvider*/LibraryThemeProvider
{
public static readonly CosmosDbExplorerThemeProvider DefaultInstance = new CosmosDbExplorerThemeProvider();
public static readonly CosmosDbExplorerThemeProvider DefaultInstance = new();

public CosmosDbExplorerThemeProvider()
: base(true)
Expand All @@ -34,7 +34,7 @@ public override void FillColorSchemeValues(Dictionary<string, string> values, Ru
throw new ArgumentNullException(nameof(colorValues));
}

bool isDarkMode = colorValues.Options.BaseColorScheme.Name == ThemeManager.BaseColorDark;
//var isDarkMode = colorValues.Options.BaseColorScheme.Name == ThemeManager.BaseColorDark;

//values.Add("CosmosDbExplorer.AvalonEdit.LinkTextForegroundBrush", isDarkMode ? Color.FromRgb(155, 109, 90).ToString() : Colors.CornflowerBlue.ToString());

Expand Down
7 changes: 6 additions & 1 deletion src/CosmosDbExplorer/ViewModels/AboutViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@ public AboutViewModel(ISystemService systemService)

public string Title { get; set; }

public static List<Author> Authors => new() { new Author("Sacha Bruttin", "sachabruttin"), new Author("savbace", "savbace") };
public static List<Author> Authors => new()
{
new Author("Sacha Bruttin", "sachabruttin"),
new Author("savbace", "savbace"),
new Author("Curlack", "Curlack")
};

public static string LicenseUrl => "https://github.com/sachabruttin/CosmosDbExplorer/blob/master/LICENSE";

Expand Down
4 changes: 2 additions & 2 deletions src/CosmosDbExplorer/ViewModels/DocumentsTabViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public class DocumentsTabViewModel : PaneWithZoomViewModel<DocumentNodeViewModel
private AsyncRelayCommand _deleteDocumentCommand;
private AsyncRelayCommand _saveDocumentCommand;
private RelayCommand _discardCommand;
private IDocumentRequestOptions _documentRequestOptions = new DocumentRequestOptions();
private readonly IDocumentRequestOptions _documentRequestOptions = new DocumentRequestOptions();

public DocumentsTabViewModel(IServiceProvider serviceProvider, IUIServices uiServices, IDialogService dialogService)
: base(uiServices)
Expand Down Expand Up @@ -464,7 +464,7 @@ async void saveFile(bool confirm, FolderDialogResult result)
Settings.Default.ExportFolder = result.Path;
Settings.Default.Save();

var tasks = new List<Task<CosmosQueryResult<JObject>>>(selectedDocuments.Count());
var tasks = new List<Task<CosmosQueryResult<JObject>>>(selectedDocuments.Count);

foreach (var document in selectedDocuments)
{
Expand Down
3 changes: 2 additions & 1 deletion src/CosmosDbExplorer/Views/DocumentsTabView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
xmlns:controls="clr-namespace:CosmosDbExplorer.Controls"
xmlns:viewmodel="clr-namespace:CosmosDbExplorer.ViewModels"
xmlns:template="clr-namespace:CosmosDbExplorer.TemplateSelectors"
xmlns:properties="clr-namespace:CosmosDbExplorer.Properties"
xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
d:DataContext="{d:DesignInstance Type=viewmodel:DocumentsTabViewModel}"
mc:Ignorable="d"
Expand Down Expand Up @@ -172,7 +173,7 @@
<LayoutDocument Title="Raw Data" CanClose="False" IconSource="{StaticResource ResultPaneIcon}">
<local:JsonEditorView x:Name="documentEditor"
DataContext="{Binding EditorViewModel}"
UseFolding="True"
UseFolding="{Binding Source={x:Static properties:Settings.Default}, Path=EnableFolding, Mode=OneWay}"
ZoomLevel="{Binding Path=DataContext.Zoom, Converter={StaticResource logConverter}, RelativeSource={RelativeSource AncestorType=UserControl, Mode=FindAncestor}}"
Visibility="{Binding HasContent, Converter={StaticResource boolToVisibilityConverter}}"/>
</LayoutDocument>
Expand Down
6 changes: 5 additions & 1 deletion src/CosmosDbExplorer/Views/ImportDocumentView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@
xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:behaviors="clr-namespace:CosmosDbExplorer.Behaviors"
xmlns:properties="clr-namespace:CosmosDbExplorer.Properties"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">

<avalonEdit:TextEditor x:Name="editor" SyntaxHighlighting="JSON"
Style="{StaticResource CosmosEditor}"
IsModified="{Binding IsDirty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Behaviors>
<behaviors:AvalonTextEditorBraceFoldingBehavior UseFolding="True" />
<behaviors:AvalonTextEditorBraceFoldingBehavior x:Name="foldingBehavior"
UseFolding="{Binding Source={x:Static properties:Settings.Default}, Path=EnableFolding, Mode=OneWay}"
FoldRootElement="{Binding Source={x:Static properties:Settings.Default}, Path=FoldingRootElement, Mode=OneWay}"
/>
<behaviors:TextAreaZoomBehavior x:Name="zoomBehavior"/>
<behaviors:AvalonTextEditorBehavior UseSearch="True" />
<behaviors:AvalonTextEditorBindingBehavior Text="{Binding Content, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
Expand Down
6 changes: 5 additions & 1 deletion src/CosmosDbExplorer/Views/JsonEditorView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:behaviors="clr-namespace:CosmosDbExplorer.Behaviors"
xmlns:viewmodel="clr-namespace:CosmosDbExplorer.ViewModels"
xmlns:properties="clr-namespace:CosmosDbExplorer.Properties"
d:DataContext="{d:DesignInstance Type=viewmodel:JsonViewerViewModel}"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
Expand All @@ -19,7 +20,10 @@
ContextMenu="{StaticResource JsonEditorContextMenu}" HorizontalScrollBarVisibility="Auto" >

<i:Interaction.Behaviors>
<behaviors:AvalonTextEditorBraceFoldingBehavior x:Name="foldingBehavior" />
<behaviors:AvalonTextEditorBraceFoldingBehavior x:Name="foldingBehavior"
UseFolding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=UseFolding}"
FoldRootElement="{Binding Source={x:Static properties:Settings.Default}, Path=FoldingRootElement, Mode=OneWay}"
/>
<behaviors:TextAreaZoomBehavior x:Name="zoomBehavior"/>
<behaviors:AvalonTextEditorBehavior UseSearch="True" />
<behaviors:AvalonTextEditorBindingBehavior Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
Expand Down
Loading

0 comments on commit ed5a83c

Please sign in to comment.