Skip to content

Commit

Permalink
Merge pull request #34 from tupunco/GUI-app-Support-folder-code-batch…
Browse files Browse the repository at this point in the history
…-conversion

`GUI-app` Support folder code batch conversion
  • Loading branch information
paulirwin authored Oct 17, 2021
2 parents cfcc7c9 + 2f01705 commit 233bc66
Show file tree
Hide file tree
Showing 3 changed files with 204 additions and 19 deletions.
1 change: 1 addition & 0 deletions JavaToCSharpGui/JavaToCSharpGui.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Caliburn.Micro" Version="4.0.173" />
<PackageReference Include="FolderBrowserForWPF" Version="1.2.0" />
<PackageReference Include="MahApps.Metro" Version="2.4.6" />
</ItemGroup>
<ItemGroup>
Expand Down
217 changes: 200 additions & 17 deletions JavaToCSharpGui/ViewModels/ShellViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
using System;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

using Caliburn.Micro;

using JavaToCSharp;

using JavaToCSharpGui.Views;

using Microsoft.Win32;

namespace JavaToCSharpGui.ViewModels
Expand All @@ -24,11 +30,23 @@ public class ShellViewModel : Screen, IShell
private bool _includeUsings = true;
private bool _includeNamespace = true;
private bool _useDebugAssertForAsserts;
private bool _isConvertEnabled = true;

#region UseFolder

private bool _useFolderConvert;
private IList<FileInfo> _javaFiles;
private string _currentJavaFile;

#endregion

public ShellViewModel()
{
base.DisplayName = "Java to C# Converter";

_isConvertEnabled = true;
_useFolderConvert = false;

_includeUsings = Properties.Settings.Default.UseUsingsPreference;
_includeNamespace = Properties.Settings.Default.UseNamespacePreference;
_useDebugAssertForAsserts = Properties.Settings.Default.UseDebugAssertPreference;
Expand Down Expand Up @@ -138,6 +156,26 @@ public bool UseDebugAssertForAsserts
}
}

public bool IsConvertEnabled
{
get => _isConvertEnabled;
set
{
_isConvertEnabled = value;
NotifyOfPropertyChange(() => IsConvertEnabled);
}
}

public bool UseFolderConvert
{
get => _useFolderConvert;
set
{
_useFolderConvert = value;
NotifyOfPropertyChange(() => UseFolderConvert);
}
}

public void AddUsing()
{
Usings.Add(_addUsingInput);
Expand Down Expand Up @@ -166,20 +204,28 @@ public void Convert()
options.WarningEncountered += Options_WarningEncountered;
options.StateChanged += Options_StateChanged;

this.IsConvertEnabled = false;
Task.Run(() =>
{
try
{
var csharp = JavaToCSharpConverter.ConvertText(JavaText, options);

Dispatcher.CurrentDispatcher.Invoke(() => this.CSharpText = csharp);
if (_useFolderConvert)
{
FolderConvert(options);
}
else
{
var csharp = JavaToCSharpConverter.ConvertText(JavaText, options);
DispatcherInvoke(() => this.CSharpText = csharp);
}
}
catch (Exception ex)
{
Dispatcher.CurrentDispatcher.Invoke(() =>
{
MessageBox.Show("There was an error converting the text to C#: " + ex.Message);
});
DispatcherInvoke(() => MessageBox.Show("There was an error converting the text to C#: " + ex.Message));
}
finally
{
DispatcherInvoke(() => this.IsConvertEnabled = true);
}
});
}
Expand All @@ -191,42 +237,170 @@ private void Options_StateChanged(object sender, ConversionStateChangedEventArgs
case ConversionState.Starting:
ConversionStateLabel = "Starting...";
break;

case ConversionState.ParsingJavaAst:
ConversionStateLabel = "Parsing Java code...";
break;

case ConversionState.BuildingCSharpAst:
ConversionStateLabel = "Building C# AST...";
break;

case ConversionState.Done:
ConversionStateLabel = "Done!";
break;

default:
break;
}
}

private static void Options_WarningEncountered(object sender, ConversionWarningEventArgs e)
private void Options_WarningEncountered(object sender, ConversionWarningEventArgs e)
{
MessageBox.Show("Java Line " + e.JavaLineNumber + ": " + e.Message, "Warning Encountered");
if (_useFolderConvert)
{
DispatcherInvoke(() =>
{
this.CSharpText = $"{ this.CSharpText } \r\n==================\r\n[WARN]out.path: { _currentJavaFile },\r\n\t\tConversionWarning-JavaLine:[{ e.JavaLineNumber}]-Message:[{ e.Message}]\r\n";
});
}
else
{
MessageBox.Show($"Java Line {e.JavaLineNumber}: {e.Message}", "Warning Encountered");
}
}

public void OpenFileDialog()
{
var ofd = new OpenFileDialog
if (_useFolderConvert)
{
OpenFolderDialog();
}
else
{
Filter = "Java Files (*.java)|*.java",
Title = "Open Java File"
var ofd = new OpenFileDialog
{
Filter = "Java Files (*.java)|*.java",
Title = "Open Java File"
};

var result = ofd.ShowDialog();
if (result.GetValueOrDefault())
{
OpenPath = ofd.FileName;
JavaText = File.ReadAllText(ofd.FileName);
}
}
}

#region FolderCodeConvert

/// <summary>
/// Folder Browser OpenFolderDialog
/// </summary>
private void OpenFolderDialog()
{
var dlg = new FolderBrowserForWPF.Dialog()
{
Title = "Folder Browser",
};

var result = ofd.ShowDialog();
if (!(dlg.ShowDialog() ?? false))
return;

var path = dlg.FileName;
var dir = new DirectoryInfo(path);
if (!dir.Exists)
{
OpenPath = string.Empty;
JavaText = string.Empty;
_javaFiles = null;

return;
}

var pDir = dir.Parent;
if (pDir == null)
{
MessageBox.Show("Fail: Root Directory !!!");
return;
}

OpenPath = path;

Task.Run(() =>
{
//list all subdir *.java
var files = dir.GetFiles("*.java", SearchOption.AllDirectories);
_javaFiles = files;

//out java path
var subStartIndex = path.Length;
var javaTexts = string.Join("\r\n", files.Select(x => x.FullName.Substring(subStartIndex)));

DispatcherInvoke(() => this.JavaText = javaTexts);
});
}

/// <summary>
/// Folder Code Convert
/// </summary>
/// <param name="options"></param>
private void FolderConvert(JavaConversionOptions options)
{
if (_javaFiles == null || options == null)
return;

var dir = new DirectoryInfo(_openPath);
var pDir = dir.Parent;
if (pDir == null)
throw new FileNotFoundException($"dir {_openPath} parent");

var dirName = dir.Name;
var outDirName = $"{dirName}_net_{DateTime.Now.Millisecond}";
var outDir = pDir.CreateSubdirectory(outDirName);
if (outDir == null || !outDir.Exists)
throw new FileNotFoundException($"outDir {outDirName}");

if (result.GetValueOrDefault())
var outDirFullName = outDir.FullName;
var subStartIndex = dir.FullName.Length;
foreach (var jFile in _javaFiles)
{
OpenPath = ofd.FileName;
JavaText = File.ReadAllText(ofd.FileName);
var jPath = jFile.Directory.FullName;
var jOutPath = outDirFullName + jPath.Substring(subStartIndex);
var jOutFileName = Path.GetFileNameWithoutExtension(jFile.Name) + ".cs";
var jOutFileFullName = Path.Combine(jOutPath, jOutFileName);

_currentJavaFile = jFile.FullName;
if (!Directory.Exists(jOutPath))
Directory.CreateDirectory(jOutPath);

var jText = File.ReadAllText(_currentJavaFile);
if (string.IsNullOrEmpty(jText))
continue;

try
{
var csText = JavaToCSharpConverter.ConvertText(jText, options);
File.WriteAllText(jOutFileFullName, csText);

DispatcherInvoke(() =>
{
this.CSharpText = $"{ this.CSharpText } \r\n==================\r\nout.path: { jOutPath },\r\n\t\tfile: {jOutFileName}";
});
}
catch (Exception ex)
{
DispatcherInvoke(() =>
{
this.CSharpText = $"{ this.CSharpText } \r\n==================\r\n[ERROR]out.path: { jOutPath },\r\nex: { ex } \r\n";
});
}
}
}

#endregion

public void CopyOutput()
{
Clipboard.SetText(CSharpText);
Expand All @@ -248,5 +422,14 @@ public void ForkMeOnGitHub()
UseShellExecute = true
});
}

/// <summary>
/// Dispatcher.CurrentDispatcher.Invoke
/// </summary>
/// <param name="callback"></param>
private void DispatcherInvoke(System.Action callback)
{
Dispatcher.CurrentDispatcher.Invoke(callback);
}
}
}
5 changes: 3 additions & 2 deletions JavaToCSharpGui/Views/ShellView.xaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Controls:MetroWindow x:Class="JavaToCSharpGui.Views.ShellView"
<Controls:MetroWindow x:Class="JavaToCSharpGui.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Micro="http://www.caliburnproject.org"
Expand Down Expand Up @@ -68,6 +68,7 @@
<CheckBox Margin="5" x:Name="IncludeUsings">Include Usings in Output</CheckBox>
<CheckBox Margin="5" x:Name="IncludeNamespace">Include Namespace in Output</CheckBox>
<CheckBox Margin="5" x:Name="UseDebugAssertForAsserts">Use Debug.Assert() for asserts</CheckBox>
<CheckBox Margin="5" x:Name="UseFolderConvert">Use Folder Convert</CheckBox>
</StackPanel>
</Grid>
</GroupBox>
Expand Down Expand Up @@ -98,7 +99,7 @@
<TextBox x:Name="JavaText" Grid.Row="2" Margin="10" VerticalScrollBarVisibility="Visible"
FontFamily="Consolas" AcceptsReturn="True"/>
</Grid>
<Button Grid.Row="1" x:Name="Convert" Grid.Column="1" Height="35" Margin="10">Convert!</Button>
<Button Grid.Row="1" x:Name="Convert" IsEnabled="{Binding IsConvertEnabled}" Grid.Column="1" Height="35" Margin="10">Convert!</Button>
<Grid Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
Expand Down

0 comments on commit 233bc66

Please sign in to comment.