This commit is contained in:
Eilon Lipton 2019-08-02 16:49:21 -07:00
Коммит 2ff67035f4
18 изменённых файлов: 847 добавлений и 0 удалений

2
.gitattributes поставляемый Normal file
Просмотреть файл

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

334
.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,334 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/

Просмотреть файл

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components" Version="3.0.0-preview8.19372.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0-preview7.19362.4" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.0.0-preview7.19362.4" />
</ItemGroup>
</Project>

Просмотреть файл

@ -0,0 +1,25 @@
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.DependencyInjection;
using System.Windows.Forms;
namespace BlinForms.Framework
{
public static class BlinForms
{
public static void Run<T>() where T: IComponent
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var serviceCollection = new ServiceCollection();
var serviceProvider = serviceCollection.BuildServiceProvider();
var renderer = new BlinFormsRenderer(serviceProvider);
renderer.Dispatcher.InvokeAsync(() =>
{
renderer.AddComponent<T>();
Application.Run(renderer.RootForm);
});
}
}
}

Просмотреть файл

@ -0,0 +1,58 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BlinForms.Framework
{
public class BlinFormsRenderer : Renderer
{
private Dictionary<int, Blontrol> _componentIdToControl = new Dictionary<int, Blontrol>();
public BlinFormsRenderer(IServiceProvider serviceProvider)
: base(serviceProvider, new LoggerFactory())
{
}
public Form RootForm { get; private set; } = new RootForm();
public override Dispatcher Dispatcher { get; }
= Dispatcher.CreateDefault();
public Task AddComponent<T>() where T: IComponent
{
var component = InstantiateComponent(typeof(T));
var componentId = AssignRootComponentId(component);
var control = _componentIdToControl[componentId] = new Blontrol(this);
RootForm.Controls.Add(control);
return RenderRootComponentAsync(componentId);
}
protected override void HandleException(Exception exception)
{
MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
protected override Task UpdateDisplayAsync(in RenderBatch renderBatch)
{
foreach (var updatedComponent in renderBatch.UpdatedComponents.Array.Take(renderBatch.UpdatedComponents.Count))
{
var control = _componentIdToControl[updatedComponent.ComponentId];
control.ApplyEdits(updatedComponent.Edits, renderBatch.ReferenceFrames);
}
return Task.CompletedTask;
}
internal Blontrol CreateControlForChildComponent(int componentId)
{
var result = new Blontrol(this);
_componentIdToControl[componentId] = result;
return result;
}
}
}

Просмотреть файл

@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using BlinForms.Framework.Controls;
using BlinForms.Framework.Elements;
using Microsoft.AspNetCore.Components.RenderTree;
namespace BlinForms.Framework
{
public class Blontrol : Control
{
private readonly BlinFormsRenderer _renderer;
private readonly List<Control> _childControls = new List<Control>();
internal static Dictionary<string, Func<BlinFormsRenderer, IBlazorNativeControl>> KnownElements { get; }
= new Dictionary<string, Func<BlinFormsRenderer, IBlazorNativeControl>>();
public Blontrol(BlinFormsRenderer renderer)
{
_renderer = renderer;
Width = 500;
Height = 500;
}
internal void ApplyEdits(ArrayBuilderSegment<RenderTreeEdit> edits, ArrayRange<RenderTreeFrame> referenceFrames)
{
foreach (var edit in edits)
{
switch (edit.Type)
{
case RenderTreeEditType.PrependFrame:
ApplyPrependFrame(edit.SiblingIndex, referenceFrames.Array, edit.ReferenceFrameIndex);
break;
case RenderTreeEditType.SetAttribute:
ApplySetAttribute(edit.SiblingIndex, ref referenceFrames.Array[edit.ReferenceFrameIndex]);
break;
default:
throw new NotImplementedException($"Not supported edit type: {edit.Type}");
}
}
}
private void ApplySetAttribute(int siblingIndex, ref RenderTreeFrame attributeFrame)
{
var target = (IBlazorNativeControl)Controls[siblingIndex];
target.ApplyAttribute(ref attributeFrame);
}
private void ApplyPrependFrame(int siblingIndex, RenderTreeFrame[] frames, int frameIndex)
{
ref var frame = ref frames[frameIndex];
switch (frame.FrameType)
{
case RenderTreeFrameType.Element:
var elementControl = (Control)CreateNativeControlForElement(frames, frameIndex);
AddChildControl(siblingIndex, elementControl);
break;
case RenderTreeFrameType.Component:
{
var childControl = _renderer.CreateControlForChildComponent(frame.ComponentId);
AddChildControl(siblingIndex, childControl);
break;
}
case RenderTreeFrameType.Markup:
if (!string.IsNullOrWhiteSpace(frame.MarkupContent))
{
throw new NotImplementedException("Nonempty markup: " + frame.MarkupContent);
}
break;
default:
throw new NotImplementedException($"Not supported frame type: {frame.FrameType}");
}
}
private void AddChildControl(int siblingIndex, Control childControl)
{
Controls.Add(childControl);
if (siblingIndex < _childControls.Count)
{
_childControls.Insert(siblingIndex, childControl);
}
else
{
_childControls.Add(childControl);
}
}
private IBlazorNativeControl CreateNativeControlForElement(RenderTreeFrame[] frames, int frameIndex)
{
ref var frame = ref frames[frameIndex];
var elementName = frame.ElementName;
var nativeControl = KnownElements[elementName](_renderer);
foreach (var attribute in AttributeUtil.ElementAttributeFrames(frames, frameIndex))
{
var attributeCopy = attribute;
nativeControl.ApplyAttribute(ref attributeCopy);
}
return nativeControl;
}
}
}

Просмотреть файл

@ -0,0 +1,54 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.RenderTree;
namespace BlinForms.Framework.Controls
{
public class Button : FormsComponentBase
{
static Button()
{
Blontrol.KnownElements.Add(typeof(Button).FullName, renderer => new BlazorButton(renderer));
}
[Parameter] public string Text { get; set; }
[Parameter] public EventCallback OnClick { get; set; }
protected override void RenderAttributes(RenderTreeBuilder builder)
{
builder.AddAttribute(1, nameof(Text), Text);
builder.AddAttribute(2, "onclick", OnClick);
}
class BlazorButton : System.Windows.Forms.Button, IBlazorNativeControl
{
public ulong ClickEventHandlerId { get; set; }
public BlazorButton(BlinFormsRenderer renderer)
{
Click += (s, e) =>
{
if (ClickEventHandlerId != default)
{
renderer.DispatchEventAsync(ClickEventHandlerId, null, new UIEventArgs());
}
};
}
public void ApplyAttribute(ref RenderTreeFrame attribute)
{
switch (attribute.AttributeName)
{
case nameof(Text):
Text = (string)attribute.AttributeValue;
break;
case "onclick":
ClickEventHandlerId = attribute.AttributeEventHandlerId;
break;
default:
FormsComponentBase.ApplyAttribute(this, ref attribute);
break;
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,34 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.RenderTree;
using System;
using System.Windows.Forms;
namespace BlinForms.Framework.Controls
{
public abstract class FormsComponentBase : ComponentBase
{
[Parameter] public int Top { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenElement(0, GetType().FullName);
RenderAttributes(builder);
builder.AddAttribute(100, nameof(Top), Top);
builder.CloseElement();
}
protected abstract void RenderAttributes(RenderTreeBuilder builder);
public static void ApplyAttribute(Control control, ref RenderTreeFrame attributeFrame)
{
switch (attributeFrame.AttributeName)
{
case nameof(Top):
control.Top = int.Parse((string)attributeFrame.AttributeValue);
break;
default:
throw new NotImplementedException($"FormsComponentBase doesn't recognize attribute '{attributeFrame.AttributeName}'");
}
}
}
}

Просмотреть файл

@ -0,0 +1,9 @@
using Microsoft.AspNetCore.Components.RenderTree;
namespace BlinForms.Framework.Controls
{
internal interface IBlazorNativeControl
{
void ApplyAttribute(ref RenderTreeFrame attribute);
}
}

Просмотреть файл

@ -0,0 +1,41 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.RenderTree;
namespace BlinForms.Framework.Controls
{
public class Label : FormsComponentBase
{
static Label()
{
Blontrol.KnownElements.Add(typeof(Label).FullName, renderer => new BlazorLabel());
}
[Parameter] public string Text { get; set; }
protected override void RenderAttributes(RenderTreeBuilder builder)
{
builder.AddAttribute(1, nameof(Text), Text);
}
class BlazorLabel : System.Windows.Forms.Label, IBlazorNativeControl
{
public BlazorLabel()
{
Width = 200;
}
public void ApplyAttribute(ref RenderTreeFrame attribute)
{
switch (attribute.AttributeName)
{
case nameof(Text):
Text = (string)attribute.AttributeValue;
break;
default:
FormsComponentBase.ApplyAttribute(this, ref attribute);
break;
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Components.RenderTree;
using System;
using System.Collections.Generic;
using System.Text;
namespace BlinForms.Framework.Elements
{
static class AttributeUtil
{
public static IEnumerable<RenderTreeFrame> ElementAttributeFrames(RenderTreeFrame[] frames, int elementFrameIndex)
{
var endIndexExcl = elementFrameIndex + frames[elementFrameIndex].ElementSubtreeLength;
for (var attributeIndex = elementFrameIndex + 1; attributeIndex < endIndexExcl; attributeIndex++)
{
var candidateFrame = frames[attributeIndex];
if (candidateFrame.FrameType == RenderTreeFrameType.Attribute)
{
yield return candidateFrame;
}
else
{
break;
}
}
}
}
}

39
BlinForms.Framework/RootForm.Designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,39 @@
namespace BlinForms.Framework
{
partial class RootForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "RootForm";
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace BlinForms.Framework
{
public partial class RootForm : Form
{
public RootForm()
{
InitializeComponent();
}
}
}

36
BlinForms.sln Normal file
Просмотреть файл

@ -0,0 +1,36 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29021.104
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlinForms.Framework", "BlinForms.Framework\BlinForms.Framework.csproj", "{D6C4DB25-814C-41A3-8BE2-23ABC929B369}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Sample", "Sample\Sample.csproj", "{2C43152F-89E3-464B-9F72-D34CB9CD37EC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{71E357C7-8DF1-447D-A0CA-084BA3F2AF83}"
ProjectSection(SolutionItems) = preProject
nuget.config = nuget.config
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D6C4DB25-814C-41A3-8BE2-23ABC929B369}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D6C4DB25-814C-41A3-8BE2-23ABC929B369}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D6C4DB25-814C-41A3-8BE2-23ABC929B369}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D6C4DB25-814C-41A3-8BE2-23ABC929B369}.Release|Any CPU.Build.0 = Release|Any CPU
{2C43152F-89E3-464B-9F72-D34CB9CD37EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2C43152F-89E3-464B-9F72-D34CB9CD37EC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2C43152F-89E3-464B-9F72-D34CB9CD37EC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2C43152F-89E3-464B-9F72-D34CB9CD37EC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A645A7FF-3F09-414D-A391-7E50C3597F05}
EndGlobalSection
EndGlobal

15
Sample/Program.cs Normal file
Просмотреть файл

@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.RenderTree;
using System;
namespace Sample
{
static class Program
{
[STAThread]
static void Main()
{
BlinForms.Framework.BlinForms.Run<WinCounter>();
}
}
}

13
Sample/Sample.csproj Normal file
Просмотреть файл

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
<RazorLangVersion>3.0</RazorLangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\BlinForms.Framework\BlinForms.Framework.csproj" />
</ItemGroup>
</Project>

11
Sample/WinCounter.razor Normal file
Просмотреть файл

@ -0,0 +1,11 @@
@using BlinForms.Framework.Controls
<Button Top="50" Text="@("Click " + count)" OnClick="@IncrementCount" />
@code {
int count = 0;
void IncrementCount()
{
count++;
}
}

13
nuget.config Normal file
Просмотреть файл

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="dotnet-core" value="https://dotnetfeed.blob.core.windows.net/dotnet-core/index.json" />
<add key="extensions" value="https://dotnetfeed.blob.core.windows.net/aspnet-extensions/index.json" />
<add key="entityframeworkcore" value="https://dotnetfeed.blob.core.windows.net/aspnet-entityframeworkcore/index.json" />
<add key="aspnetcore-tooling" value="https://dotnetfeed.blob.core.windows.net/aspnet-aspnetcore-tooling/index.json" />
<add key="aspnetcore" value="https://dotnetfeed.blob.core.windows.net/aspnet-aspnetcore/index.json" />
<add key="aspnet-blazor" value="https://dotnetfeed.blob.core.windows.net/aspnet-blazor/index.json" />
<add key="NuGet.org" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>