Skip to content

Commit

Permalink
Add: CSharp code compiler
Browse files Browse the repository at this point in the history
  • Loading branch information
zbx1425 committed Jan 17, 2021
1 parent e103a81 commit 08c5b35
Show file tree
Hide file tree
Showing 40 changed files with 3,796 additions and 206 deletions.
20 changes: 16 additions & 4 deletions BlocklyAtsGui/BaseBrowser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace BlocklyATS {

Expand All @@ -26,13 +27,17 @@ public virtual void BindTo(Control parent) {
}

public static BaseBrowser AcquireInstance(string url = "about:blank") {
#if MONO
return new WinformBrowser(url);
#else
var CEFAvailable = File.Exists(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),
"x86", "CefSharp.dll"));
if (CEFAvailable) {
return new CefBrowser(url);
} else {
return new WinformBrowser(url);
}
#endif
}

public static string EscapeJsString(string s) {
Expand Down Expand Up @@ -77,16 +82,23 @@ public void BkyResetWorkspace() {
InvokeScript("batsWkspReset();");
}

public string BkySaveWorkspace() {
return InvokeScript("batsWkspSave();").ToString();
public XElement BkySaveWorkspace() {
var element = XElement.Parse(InvokeScript("batsWkspSave();").ToString());
element.RemoveAttributes();
return element;
}

public void BkyLoadWorkspace(string bkyxml) {
InvokeScript(string.Format("batsWkspLoad('{0}');", EscapeJsString(bkyxml)));
public void BkyLoadWorkspace(XElement bkyxml) {
var arg = EscapeJsString(bkyxml.ToString(SaveOptions.DisableFormatting));
InvokeScript(string.Format("batsWkspLoad('{0}');", arg));
}

public string BkyExportLua() {
return InvokeScript("batsWkspExportLua();").ToString();
}

public string BkyExportCSharp() {
return InvokeScript("batsWkspExportCSharp();").ToString();
}
}
}
34 changes: 33 additions & 1 deletion BlocklyAtsGui/BlocklyAtsGui.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\bin_debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DefineConstants>TRACE;DEBUG;MONO</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
Expand Down Expand Up @@ -58,6 +58,25 @@
<ItemGroup>
<Compile Include="CefBrowser.cs" />
<Compile Include="CompilerFunction.cs" />
<Compile Include="CompilerConfig.cs" />
<Compile Include="FormAbout.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FormAbout.Designer.cs">
<DependentUpon>FormAbout.cs</DependentUpon>
</Compile>
<Compile Include="FormCompilerConfig.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FormCompilerConfig.Designer.cs">
<DependentUpon>FormCompilerConfig.cs</DependentUpon>
</Compile>
<Compile Include="FormDebug.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FormDebug.Designer.cs">
<DependentUpon>FormDebug.cs</DependentUpon>
</Compile>
<Compile Include="FormMain.cs">
<SubType>Form</SubType>
</Compile>
Expand All @@ -70,6 +89,15 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WinformBrowser.cs" />
<Compile Include="Workspace.cs" />
<EmbeddedResource Include="FormAbout.resx">
<DependentUpon>FormAbout.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FormCompilerConfig.resx">
<DependentUpon>FormCompilerConfig.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FormDebug.resx">
<DependentUpon>FormDebug.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FormMain.resx">
<DependentUpon>FormMain.cs</DependentUpon>
</EmbeddedResource>
Expand All @@ -81,6 +109,7 @@
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
Expand All @@ -96,6 +125,9 @@
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<None Include="Resources\Attribution.txt" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>
Expand Down
4 changes: 3 additions & 1 deletion BlocklyAtsGui/CefBrowser.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#if !MONO
using CefSharp;
using CefSharp.WinForms;
using System;
Expand Down Expand Up @@ -28,7 +29,7 @@ public KeyboardHandler(CefBrowser browser) {

public bool OnKeyEvent(IWebBrowser chromiumWebBrowser, CefSharp.IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey) {
if (type == KeyType.KeyUp && Enum.IsDefined(typeof(Keys), windowsKeyCode)) {
parent.KeyDown?.Invoke(browser, new PreviewKeyDownEventArgs((Keys)windowsKeyCode));
parent.browser.BeginInvoke((Action)(() => parent.KeyDown?.Invoke(browser, new PreviewKeyDownEventArgs((Keys)windowsKeyCode))));
}
return false;
}
Expand Down Expand Up @@ -94,3 +95,4 @@ public void ShowDevTools() {
}
}
}
#endif
68 changes: 68 additions & 0 deletions BlocklyAtsGui/CompilerConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace BlocklyATS {

public class CompilerConfig {

public bool ShouldCompileAnyCpu { get; set; }

public bool ShouldCompilex86 { get; set; }

public bool ShouldCompilex64 { get; set; }

public string CompilePathAnyCpu { get; set; }

public string CompilePathx86 { get; set; }

public string CompilePathx64 { get; set; }

public string GamePath { get; set; }

public string GameArgs { get; set; }

public CompilerConfig Clone() {
return (CompilerConfig)this.MemberwiseClone();
}

public Process GetGameProcess() {
var path = GamePath;
if (string.IsNullOrEmpty(path)) {
if (PlatformFunction.IsWindows()) {
const string InnoAppID = "{D617A45D-C2F6-44D1-A85C-CA7FFA91F7FC}_is1";
string[] InstallLocations = new RegistryKey[] {
Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + InnoAppID),
Registry.CurrentUser.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + InnoAppID),
Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + InnoAppID),
Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + InnoAppID),
}.Select(regKey => regKey != null ? regKey.GetValue("InstallLocation", null) : null).OfType<string>().Distinct().ToArray();
foreach (string location in InstallLocations) {
string assemblyFile = Path.Combine(location, "OpenBve.exe");
if (!File.Exists(assemblyFile)) continue;
path = assemblyFile;
break;
}
} else {
// TODO: Support them
}
}
if (string.IsNullOrEmpty(path) || !File.Exists(path)) {
throw new FileNotFoundException(null, path);
}
return new Process() {
StartInfo = new ProcessStartInfo {
FileName = path,
UseShellExecute = false,
Arguments = GameArgs
}
};
}
}
}
34 changes: 31 additions & 3 deletions BlocklyAtsGui/CompilerFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace BlocklyATS {

static class CompilerFunction {

public static string appDir = Path.GetDirectoryName(Application.ExecutablePath);

private static Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken)) {
public static Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default(CancellationToken)) {
if (process.HasExited) return Task.CompletedTask;

var tcs = new TaskCompletionSource<object>();
Expand All @@ -27,7 +29,7 @@ static class CompilerFunction {
return process.HasExited ? Task.CompletedTask : tcs.Task;
}

public static async Task CompileLua(string luaScript, string outputPath, string arch) {
public static async Task CompileLua(string script, string outputPath, string arch) {
/*var proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = Path.Combine(appDir, "bin", "luac" + arch + ".exe"),
Expand Down Expand Up @@ -57,7 +59,7 @@ public static async Task CompileLua(string luaScript, string outputPath, string
await boilerplateStream.CopyToAsync(outStream);
//await proc.StandardOutput.BaseStream.CopyToAsync(outStream);
byte[] confusion = { 0x11, 0x45, 0x14, 0x19, 0x19, 0x81, 0x14, 0x25 };
byte[] srcCode = Encoding.UTF8.GetBytes(luaScript);
byte[] srcCode = Encoding.UTF8.GetBytes(script);
for (int i = 0; i < srcCode.Length; i++) srcCode[i] ^= confusion[i % 8];
await outStream.WriteAsync(srcCode, 0, srcCode.Length);
boilerplateStream.Close();
Expand All @@ -74,5 +76,31 @@ public static async Task CompileLua(string luaScript, string outputPath, string
File.Delete(Path.Combine(Path.GetDirectoryName(outputPath), luabin));
}*/
}

public static void CompileCSharp(string script, string outputPath) {
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters() {
IncludeDebugInformation = false,
GenerateExecutable = false,
OutputAssembly = outputPath
};
string[] assemblies = {
"System", "System.Core", "System.Data", "mscorlib",
"Microsoft.CSharp", "System.Windows.Forms",
Path.Combine(appDir, "bin", "OpenBveApi")
};

foreach (string a in assemblies) {
parameters.ReferencedAssemblies.Add(a + ".dll");
}
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, script);
if (results.Errors.HasErrors) {
StringBuilder sb = new StringBuilder();
foreach (CompilerError error in results.Errors) {
sb.AppendLine(error.ToString());
}
throw new Exception(sb.ToString());
}
}
}
}
Loading

0 comments on commit 08c5b35

Please sign in to comment.