Skip to content

Commit

Permalink
Merge pull request #4 from aglasencnik/dev
Browse files Browse the repository at this point in the history
Implemented graph preview functionality
  • Loading branch information
aglasencnik authored Jan 28, 2024
2 parents afb982f + 645032d commit 949fc35
Show file tree
Hide file tree
Showing 8 changed files with 152 additions and 21 deletions.
74 changes: 74 additions & 0 deletions GraphvizVS/CommandHandlers/SaveCommandHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using System.ComponentModel.Composition;
using System.IO;
using GraphvizVS.ToolWindows;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text;

namespace GraphvizVS.CommandHandlers;

/// <summary>
/// Represents the command handler for save command.
/// </summary>
[Export(typeof(ICommandHandler))]
[Name(nameof(TypeCharCommandHandler))]
[ContentType(ContentTypes.Text)]
[TextViewRole(PredefinedTextViewRoles.PrimaryDocument)]
internal sealed class SaveCommandHandler : ICommandHandler<SaveCommandArgs>
{
/// <summary>
/// Gets the display name of the command handler.
/// </summary>
public string DisplayName => Vsix.Name;

/// <summary>
/// Determines whether command handler is enabled.
/// </summary>
/// <param name="args">SaveCommandArgs object.</param>
/// <returns>CommandState object.</returns>
public CommandState GetCommandState(SaveCommandArgs args) => CommandState.Available;

/// <summary>
/// Executes command handler.
/// </summary>
/// <param name="args">TypeCharCommandArgs object.</param>
/// <param name="executionContext">CommandExecutionContext object.</param>
/// <returns>Whether key was overriden successfully.</returns>
public bool ExecuteCommand(SaveCommandArgs args, CommandExecutionContext executionContext)
{
try
{
var fileName = args.SubjectBuffer.GetFileName();
if (string.IsNullOrWhiteSpace(fileName))
return false;

var fileExtension = Path.GetExtension(fileName);
if (string.IsNullOrWhiteSpace(fileExtension) || fileExtension.ToLower() != ".dot")
return false;

ThreadHelper.ThrowIfNotOnUIThread();
var package = ServiceProvider.GlobalProvider.GetService(typeof(GraphvizVSPackage)) as GraphvizVSPackage;
if (package is null)
return false;

var window = package.FindToolWindow(typeof(GraphPreviewWindow.Pane), 0, false);
if (window is null)
return false;

var control = window.Content as GraphPreviewWindowControl;
if (control is null)
return false;

control.UpdatePreviewWindow(fileName).GetAwaiter();

return false;
}
catch (Exception ex)
{
ex.Log();
return false;
}
}
}
20 changes: 10 additions & 10 deletions GraphvizVS/CommandHandlers/TypeCharCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,29 @@ internal sealed class TypeCharCommandHandler : ICommandHandler<TypeCharCommandAr
/// </summary>
public string DisplayName => Vsix.Name;

/// <summary>
/// Determines whether command handler is enabled.
/// </summary>
/// <param name="args">TypeCharCommandArgs object.</param>
/// <returns>CommandState object.</returns>
public CommandState GetCommandState(TypeCharCommandArgs args) => CommandState.Available;

/// <summary>
/// Executes command handler.
/// </summary>
/// <param name="args">TypeCharCommandArgs object</param>
/// <param name="executionContext">CommandExecutionContext object</param>
/// <param name="args">TypeCharCommandArgs object.</param>
/// <param name="executionContext">CommandExecutionContext object.</param>
/// <returns>Whether key was overriden successfully.</returns>
public bool ExecuteCommand(TypeCharCommandArgs args, CommandExecutionContext executionContext)
{
var typedChar = args.TypedChar;
var fileExtension = Path.GetExtension(args.SubjectBuffer.GetFileName() ?? "");
if (!string.IsNullOrWhiteSpace(fileExtension) && (fileExtension == ".dot" || fileExtension == ".DOT") && (typedChar == '/' || typedChar == '-'))
if (!string.IsNullOrWhiteSpace(fileExtension) && fileExtension.ToLower() == ".dot" && (typedChar == '/' || typedChar == '-'))
{
args.TextView.TextBuffer.Insert(args.TextView.Caret.Position.BufferPosition, typedChar == '/' ? "//" : "->");
return true;
}

return false;
}

/// <summary>
/// Determines whether command handler is enabled.
/// </summary>
/// <param name="args">TypeCharCommandArgs object</param>
/// <returns>CommandState object</returns>
public CommandState GetCommandState(TypeCharCommandArgs args) => CommandState.Available;
}
5 changes: 5 additions & 0 deletions GraphvizVS/GraphvizVS.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Compile Include="CommandHandlers\SaveCommandHandler.cs" />
<Compile Include="CommandHandlers\TypeCharCommandHandler.cs" />
<Compile Include="Commands\ExportGraphCommand.cs" />
<Compile Include="Commands\OpenGraphPreviewWindowCommand.cs" />
Expand Down Expand Up @@ -654,6 +655,7 @@
<Reference Include="System.Design" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Xaml" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
Expand All @@ -663,6 +665,9 @@
<PackageReference Include="Community.VisualStudio.VSCT" Version="16.0.29.6" PrivateAssets="all" />
<PackageReference Include="Community.VisualStudio.Toolkit.17" Version="17.0.430" ExcludeAssets="Runtime" />
<PackageReference Include="Microsoft.VSSDK.BuildTools" Version="17.0.5232" />
<PackageReference Include="SharpVectors">
<Version>1.8.3</Version>
</PackageReference>
</ItemGroup>
<ItemGroup />
<ItemGroup>
Expand Down
4 changes: 3 additions & 1 deletion GraphvizVS/GraphvizVSPackage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ namespace GraphvizVS;
[Guid(PackageGuids.GraphvizVSString)]
[ProvideOptionPage(typeof(OptionsProvider.GeneralOptionsProvider), "GraphvizVS", "General", 0, 0, true)]
[ProvideProfile(typeof(OptionsProvider.GeneralOptionsProvider), "GraphvizVS", "General", 0, 0, true)]
[ProvideToolWindow(typeof(GraphPreviewWindow.Pane))]
[ProvideToolWindow(typeof(GraphPreviewWindow.Pane), Style = VsDockStyle.Linked, Window = WindowGuids.Toolbox)]
[ProvideUIContextRule(PackageGuids.uiContextSupportedFilesString, name: "Supported Files", expression: "DOT", termNames: ["DOT", "DOT"], termValues: ["HierSingleSelectionName:.dot$", "HierSingleSelectionName:.DOT$"])]
[ProvideService(typeof(GraphvizVSPackage), IsAsyncQueryable = true)]
public sealed class GraphvizVSPackage : ToolkitPackage
{
/// <summary>
Expand All @@ -33,5 +34,6 @@ protected override async Task InitializeAsync(CancellationToken cancellationToke
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
await this.RegisterCommandsAsync();
this.RegisterToolWindows();
AddService(typeof(GraphvizVSPackage), (_, _, _) => Task.FromResult<object>(this), promote: true);
}
}
6 changes: 1 addition & 5 deletions GraphvizVS/ToolWindows/GraphPreviewWindowControl.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@
d:DesignWidth="300"
Name="GraphPreview">
<Grid>
<Button Content="Click me!"
Click="button1_Click"
Width="120"
Height="80"
Name="button1" />
<Image Name="PreviewImage" Stretch="Uniform" />
</Grid>
</UserControl>
60 changes: 57 additions & 3 deletions GraphvizVS/ToolWindows/GraphPreviewWindowControl.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
using System.Windows;
using Microsoft.VisualStudio.Imaging;
using System.IO;
using System.Windows.Controls;
using Microsoft.VisualStudio.Shell.Interop;
using CliWrap;
using GraphvizVS.Helpers;
using GraphvizVS.Options;
using System.Collections.Generic;
using System.Windows.Media;
using CliWrap.Buffered;
using SharpVectors.Converters;
using SharpVectors.Renderers.Wpf;

namespace GraphvizVS.ToolWindows;

Expand All @@ -13,8 +23,52 @@ public GraphPreviewWindowControl()
InitializeComponent();
}

private void button1_Click(object sender, RoutedEventArgs e)
public async Task UpdatePreviewWindow(string documentPath)
{
VS.MessageBox.Show("GraphPreviewWindowControl", "Button clicked");
try
{
if (!File.Exists(documentPath))
return;

var flags = new List<string>();

if (!string.IsNullOrWhiteSpace(GeneralOptions.Instance.AdditionalFlags))
flags.Add(GeneralOptions.Instance.AdditionalFlags);

flags.Add("-Tsvg");
flags.Add(documentPath);

var result = await Cli.Wrap(CommandLineHelper.GetEnginePath())
.WithArguments(flags)
.ExecuteBufferedAsync();

if (!result.IsSuccess)
return;

var tempFileName = Path.GetTempFileName();
File.WriteAllText(tempFileName, result.StandardOutput);

var settings = new WpfDrawingSettings
{
IncludeRuntime = true
};
var converter = new FileSvgReader(settings);
var drawing = converter.Read(tempFileName);
PreviewImage.Source = new DrawingImage(drawing);

File.Delete(tempFileName);
}
catch (Exception ex)
{
var infoBar = await VS.InfoBar.CreateAsync(
ToolWindowGuids80.SolutionExplorer,
new InfoBarModel([new InfoBarTextSpan("Something went wrong while loading graph preview!")], KnownMonikers.DiagramError)
);

if (infoBar != null)
await infoBar.TryShowInfoBarUIAsync();

await ex.LogAsync();
}
}
}
2 changes: 1 addition & 1 deletion GraphvizVS/source.extension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ internal sealed partial class Vsix
public const string Name = "GraphvizVS";
public const string Description = @"Streamline your Graphviz graph creation in Visual Studio with GraphvizVS; instantly preview and export diagrams with added IntelliSense support for quicker editing.";
public const string Language = "en-US";
public const string Version = "0.1";
public const string Version = "1.0.0";
public const string Author = "Amadej Glasenčnik";
public const string Tags = "graphviz, visual-studio, tools, graphs, vsix, dot-language";
}
Expand Down
2 changes: 1 addition & 1 deletion GraphvizVS/source.extension.vsixmanifest
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" ?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Id="GraphvizVS.7e008693-51b2-4c63-9a07-b7d03e14965e" Version="0.1" Language="en-US" Publisher="Amadej Glasenčnik" />
<Identity Id="GraphvizVS.7e008693-51b2-4c63-9a07-b7d03e14965e" Version="1.0.0" Language="en-US" Publisher="Amadej Glasenčnik" />
<DisplayName>GraphvizVS</DisplayName>
<Description xml:space="preserve">Streamline your Graphviz graph creation in Visual Studio with GraphvizVS; instantly preview and export diagrams with added IntelliSense support for quicker editing.</Description>
<MoreInfo>https://github.com/aglasencnik/GraphvizVS</MoreInfo>
Expand Down

0 comments on commit 949fc35

Please sign in to comment.