Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update he 优化 winform 热执行 #350

Merged
merged 1 commit into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ void ISourceGenerator.Execute(GeneratorExecutionContext context)

string coreScript = "HEProxy.SetProjectKind(HEProjectKind.Console);";
string winformAndwpfLoggerScript = @"
string debugFilePath = Path.Combine(VSCSharpProjectInfomation.HEOutputPath,""Debug.txt"");
if (Directory.Exists(VSCSharpProjectInfomation.HEOutputPath))
string debugFilePath = Path.Combine(VSCSProjectInfoHelper.HEOutputPath,""Debug.txt"");
if (Directory.Exists(VSCSProjectInfoHelper.HEOutputPath))
{
var files = Directory.GetFiles(VSCSharpProjectInfomation.HEOutputPath);
var files = Directory.GetFiles(VSCSProjectInfoHelper.HEOutputPath);
foreach (var file in files)
{
File.Delete(file);
Expand Down Expand Up @@ -51,7 +51,7 @@ void ISourceGenerator.Execute(GeneratorExecutionContext context)
HEProxy.SetProjectKind(HEProjectKind.Winform);
HEProxy.ExcludeGlobalUsing(""System.Windows.Controls"");
HEProxy.ExcludeGlobalUsing(""System.Windows"");
DelegateHelper<System.Windows.Forms.FormCollection, System.Windows.Forms.Form>.GetDelegate(""Remove"", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
HEDelegateHelper<System.Windows.Forms.FormCollection, System.Windows.Forms.Form>.GetDelegate(""Remove"", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
";
}
else
Expand All @@ -75,6 +75,7 @@ void ISourceGenerator.Execute(GeneratorExecutionContext context)
string proxyMethodContent = $@"
//#if DEBUG
using System.IO;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Natasha.CSharp.HotExecutor.Component;
using Natasha.CSharp.Extension.HotExecutor;
Expand All @@ -91,6 +92,7 @@ internal static void PreMain()

{coreScript}
HEProxy.SetCompileInitAction(()=>{{

NatashaManagement.RegistDomainCreator<NatashaDomainCreator>();
NatashaManagement.Preheating((asmName, @namespace) => !string.IsNullOrWhiteSpace(@namespace) && (@namespace.StartsWith(""Microsoft.VisualBasic"")|| HEProxy.IsExcluded(@namespace)),true, true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

public static class HEProxy
{
public static bool IsRuntimeFirstRun = true;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

Unused Variable: IsRuntimeFirstRun

The variable IsRuntimeFirstRun is declared but not used anywhere else in the codebase. Please verify its necessity or consider removing it if it is not needed.

  • src/Natasha.CSharp/Extension/HotExecutor/Natasha.CSharp.HotExecutor/HEProxy.cs: Line 15
Analysis chain

LGTM! Verify the usage of IsRuntimeFirstRun.

The addition of the IsRuntimeFirstRun variable looks good.

However, ensure that this variable is properly utilized in the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `IsRuntimeFirstRun` in the codebase.

# Test: Search for the variable usage. Expect: Proper utilization of the variable.
rg --type-add csharp --type csharp 'IsRuntimeFirstRun'

Length of output: 114


Script:

#!/bin/bash
# Description: Verify the usage of `IsRuntimeFirstRun` in the codebase.

# Test: Search for the variable usage. Expect: Proper utilization of the variable.
rg 'IsRuntimeFirstRun'

Length of output: 150

public static object? ObjectInstance;
public static Assembly CurrentAssembly = default!;
private static string _argumentsMethodName = "ProxyMainArguments";
private static readonly ConcurrentDictionary<string, SyntaxTree> _fileSyntaxTreeCache = new();
Expand Down Expand Up @@ -237,6 +239,7 @@ public static void Run()
_cs0104UsingCache[file] = _cs0104TriviaPlugin.ExcludeUsings;
//从默认Using缓存中排除 CS0104
root = UsingsHandler.Handle(root, _cs0104UsingCache);
ShowMessage(root.ToFullString());
return CSharpSyntaxTree.Create(root, _currentOptions, file, Encoding.UTF8);
}
if (root != reBuildRoot)
Expand Down Expand Up @@ -342,6 +345,7 @@ private static async Task HotExecute()
instance = Activator.CreateInstance(typeInfo);
}

ShowMessage($"执行主入口回调方法....");
if (_asyncTriviaPlugin.IsAsync)
{
Task mainTask;
Expand Down Expand Up @@ -377,9 +381,9 @@ private static async Task HotExecute()
}


ShowMessage($"执行主入口回调方法....");
ShowMessage($"执行入口回调方法....");
_endCallback?.Invoke();
ShowMessage($"入口回调方法执行完毕.");
ShowMessage($"执行系列方法执行完毕.");

}
catch (Exception ex)
Expand Down Expand Up @@ -456,6 +460,7 @@ private async static Task ReAnalysisFiles()

public static void SetProjectKind(HEProjectKind kind)
{
_proxyMethodPlugin.SetProjectKind(kind);
_projectKind = kind;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ public async Task WriteUtf8FileAsync(string msg)
{
await _writer.WriteLineAsync(msg);
isWritten = true;
_fileLock.ReleaseLock();
await _writer.FlushAsync();
}
_fileLock.ReleaseLock();
return;
}
catch (Exception)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ internal static class WinformRewriter
System.Threading.Tasks.Task.Run(() =>
{{
System.Windows.Forms.Application.ExitThread();
while(!DiposeWindows()){{}};
var __heProxInstance = {runArgumentScript};
System.Windows.Forms.Form tempForm;
if (__heProxInstance is System.Windows.Forms.Form)
Expand All @@ -60,7 +59,9 @@ internal static class WinformRewriter
else
{{
tempForm = (System.Windows.Forms.Form)(typeof(System.Windows.Forms.ApplicationContext).GetProperty(""MainForm"")!.GetValue(__heProxInstance)!);
}}
}}
System.Diagnostics.Debug.WriteLine($""当前主窗体程序集为 {{tempForm.GetType().Assembly.FullName}}!"");
System.Diagnostics.Debug.WriteLine($""当前主窗体为 {{tempForm.Name}}!"");
tempForm.FormClosed += (s, e) =>
{{
if (!HEProxy.IsHotCompiling)
Expand All @@ -72,35 +73,88 @@ internal static class WinformRewriter
}}
}}
}};

Action? removeHandler = null;
System.EventHandler handler = (s, e) =>
{{
while(!DiposeWindows(tempForm)){{}};
removeHandler?.Invoke();

}};
removeHandler = () => {{

tempForm.Shown -= handler;

}};

tempForm.Shown += handler;
try{{

System.Diagnostics.Debug.WriteLine(tempForm.button4.Text);
System.Windows.Forms.Application.Run(__heProxInstance);

}}catch(System.Exception ex)
{{
HEProxy.ShowMessage(ex.Message);
System.Diagnostics.Debug.WriteLine(""启动出错"" + ex.Message);
}}

static bool DiposeWindows()
static bool DiposeWindows(System.Windows.Forms.Form aliveForm)
{{
try{{
for (int i = 0; i < System.Windows.Forms.Application.OpenForms.Count; i++)
System.Collections.Generic.HashSet<System.Windows.Forms.Form> forms = [];
System.Collections.Generic.HashSet<System.Windows.Forms.Form> removeForms = [];
if(HEProxy.ObjectInstance!=null)
{{
try{{
forms.Add((System.Windows.Forms.Form)HEProxy.ObjectInstance);
}}
forms.Add(aliveForm);
System.Diagnostics.Debug.WriteLine(System.Windows.Forms.Application.OpenForms.Count);

int i = 0;
do
{{
try
{{

var form = System.Windows.Forms.Application.OpenForms[i];
if (form!=null)
if(forms.Contains(form))
{{
HEProxy.ShowMessage($""当前将被注销的开放窗体 {{form.Name}}"");
form.Dispose();
Natasha.CSharp.HotExecutor.Component.DelegateHelper<System.Windows.Forms.FormCollection, System.Windows.Forms.Form>.Execute.Invoke(System.Windows.Forms.Application.OpenForms, form);
i+=1;
continue;
}}
}}catch{{

if (form != null && form != aliveForm)
{{

if(HEProxy.ObjectInstance==null){{
HEProxy.ObjectInstance = form;
form.BeginInvoke(new Action(() => {{
System.Diagnostics.Debug.WriteLine($""当前将被隐藏的开放窗体 {{form.Name}}!"");
form.Hide();
removeForms.Add(form);
}}));
forms.Add(form);
}}else {{
form.BeginInvoke(new Action(() => {{
System.Diagnostics.Debug.WriteLine($""当前将被注销的开放窗体 {{form.Name}}!"");
form.Dispose();
removeForms.Add(form);
}}));
forms.Add(form);
}}
}}

}}
}}
}}catch{{
return false;
catch (System.Exception ex)
{{
System.Diagnostics.Debug.WriteLine($""注销窗体出错 {{ex.Message}}!"");
return false;
}}
}} while (System.Windows.Forms.Application.OpenForms.Count > i);

foreach(var removeForm in removeForms)
{{
Natasha.CSharp.HotExecutor.Component.HEDelegateHelper<System.Windows.Forms.FormCollection, System.Windows.Forms.Form>.Execute.Invoke(System.Windows.Forms.Application.OpenForms, removeForm);
}}

return true;
}}
}});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ static HECompiler()
CompilerBinderFlags.SuppressObsoleteChecks));
_builderCache
.UseSmartMode()
.WithFileOutput()
.WithoutSemanticCheck()
.WithPreCompilationOptions()
.WithoutPreCompilationReferences()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ public void DeployMonitor()

_mainWatcher.Renamed += async (sender, e) =>
{
#if DEBUG
HEProxy.ShowMessage($"Renamed: {e.OldFullPath} -> {e.FullPath}");
#endif
if (PreFunction())
{
return;
Expand All @@ -106,13 +109,10 @@ public void DeployMonitor()
{
await ExecuteAfterFunction();

}else if (e.OldFullPath.EndsWith(".cs"))
}else if (e.FullPath.EndsWith(".cs"))
{
if (e.FullPath.EndsWith(".cs"))
if (e.OldFullPath.EndsWith(".cs"))
{
#if DEBUG
HEProxy.ShowMessage($"Renamed: {e.OldFullPath} -> {e.FullPath}");
#endif
_compileLock.GetAndWaitLock();
if (VSCSProjectInfoHelper.CheckFileAvailiable(e.FullPath))
{
Expand All @@ -125,15 +125,12 @@ public void DeployMonitor()
_compileLock.ReleaseLock();
await ExecuteAfterFunction();
}
else if (e.FullPath.StartsWith(e.OldFullPath) && e.FullPath.EndsWith(".TMP"))
else
{
#if DEBUG
HEProxy.ShowMessage($"Renamed: {e.OldFullPath} -> {e.FullPath}");
#endif
if (VSCSProjectInfoHelper.CheckFileAvailiable(e.OldFullPath))
if (VSCSProjectInfoHelper.CheckFileAvailiable(e.FullPath))
{
_compileLock.GetAndWaitLock();
ChangeFileAction(e.OldFullPath);
ChangeFileAction(e.FullPath);
_compileLock.ReleaseLock();
await ExecuteAfterFunction();
}
Expand Down
Loading