Compare commits

...

5 Commits

Author SHA1 Message Date
lihanbo 33d13b62f1 增加MarkDown支持 2025-02-28 14:29:34 +08:00
lihanbo ae573e0ecb 移除不必要的控件 2025-02-28 10:27:16 +08:00
lihanbo 1aaed2ce0e 独立ChatMessage类 2025-02-28 10:26:58 +08:00
lihanbo 6c02a38c3f 切换项目结构 2025-02-28 09:20:53 +08:00
lihanbo a6d1c966d8 引入AI支持(火山引擎) 2025-02-28 08:41:23 +08:00
103 changed files with 3158 additions and 31 deletions

Binary file not shown.

Binary file not shown.

BIN
.vs/ExcelHelper/v17/.suo Normal file

Binary file not shown.

BIN
.vs/ExcelHelper/v17/.wsuo Normal file

Binary file not shown.

View File

@ -0,0 +1,65 @@
{
"Version": 1,
"WorkspaceRootPath": "D:\\code\\source\\repos\\ExcelHelper\\",
"Documents": [
{
"AbsoluteMoniker": "D:0:0:{A2FE74E1-B743-11D0-AE1A-00A0C90FFFC3}|\u003CMiscFiles\u003E|D:\\code\\source\\repos\\ExcelHelper\\src\\ExcelHelper\\ExcelHelper.csproj||{FA3CD31E-987B-443A-9B81-186104E8DAC1}",
"RelativeMoniker": "D:0:0:{A2FE74E1-B743-11D0-AE1A-00A0C90FFFC3}|\u003CMiscFiles\u003E|solutionrelative:src\\ExcelHelper\\ExcelHelper.csproj||{FA3CD31E-987B-443A-9B81-186104E8DAC1}"
}
],
"DocumentGroupContainers": [
{
"Orientation": 0,
"VerticalTabListWidth": 256,
"DocumentGroups": [
{
"DockedWidth": 200,
"SelectedChildIndex": 7,
"Children": [
{
"$type": "Bookmark",
"Name": "ST:128:0:{1fc202d4-d401-403c-9834-5b218574bb67}"
},
{
"$type": "Bookmark",
"Name": "ST:128:0:{13b12e3e-c1b4-4539-9371-4fe9a0d523fc}"
},
{
"$type": "Bookmark",
"Name": "ST:129:0:{1fc202d4-d401-403c-9834-5b218574bb67}"
},
{
"$type": "Bookmark",
"Name": "ST:133:0:{1fc202d4-d401-403c-9834-5b218574bb67}"
},
{
"$type": "Bookmark",
"Name": "ST:134:0:{1fc202d4-d401-403c-9834-5b218574bb67}"
},
{
"$type": "Bookmark",
"Name": "ST:131:0:{116d2292-e37d-41cd-a077-ebacac4c8cc4}"
},
{
"$type": "Bookmark",
"Name": "ST:0:0:{aa2115a1-9712-457b-9047-dbb71ca2cdd2}"
},
{
"$type": "Document",
"DocumentIndex": 0,
"Title": "ExcelHelper.csproj",
"DocumentMoniker": "D:\\code\\source\\repos\\ExcelHelper\\src\\ExcelHelper\\ExcelHelper.csproj",
"RelativeDocumentMoniker": "src\\ExcelHelper\\ExcelHelper.csproj",
"ToolTip": "D:\\code\\source\\repos\\ExcelHelper\\src\\ExcelHelper\\ExcelHelper.csproj",
"RelativeToolTip": "src\\ExcelHelper\\ExcelHelper.csproj",
"ViewState": "AgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
"Icon": "ae27a6b0-e345-4288-96df-5eaf394ee369.000758|",
"WhenOpened": "2025-02-28T01:19:10.825Z",
"EditorCaption": ""
}
]
}
]
}
]
}

View File

@ -0,0 +1,65 @@
{
"Version": 1,
"WorkspaceRootPath": "D:\\code\\source\\repos\\ExcelHelper\\",
"Documents": [
{
"AbsoluteMoniker": "D:0:0:{A2FE74E1-B743-11D0-AE1A-00A0C90FFFC3}|\u003CMiscFiles\u003E|D:\\code\\source\\repos\\ExcelHelper\\src\\ExcelHelper\\ExcelHelper.csproj||{FA3CD31E-987B-443A-9B81-186104E8DAC1}",
"RelativeMoniker": "D:0:0:{A2FE74E1-B743-11D0-AE1A-00A0C90FFFC3}|\u003CMiscFiles\u003E|solutionrelative:src\\ExcelHelper\\ExcelHelper.csproj||{FA3CD31E-987B-443A-9B81-186104E8DAC1}"
}
],
"DocumentGroupContainers": [
{
"Orientation": 0,
"VerticalTabListWidth": 256,
"DocumentGroups": [
{
"DockedWidth": 200,
"SelectedChildIndex": 7,
"Children": [
{
"$type": "Bookmark",
"Name": "ST:128:0:{1fc202d4-d401-403c-9834-5b218574bb67}"
},
{
"$type": "Bookmark",
"Name": "ST:128:0:{13b12e3e-c1b4-4539-9371-4fe9a0d523fc}"
},
{
"$type": "Bookmark",
"Name": "ST:129:0:{1fc202d4-d401-403c-9834-5b218574bb67}"
},
{
"$type": "Bookmark",
"Name": "ST:133:0:{1fc202d4-d401-403c-9834-5b218574bb67}"
},
{
"$type": "Bookmark",
"Name": "ST:134:0:{1fc202d4-d401-403c-9834-5b218574bb67}"
},
{
"$type": "Bookmark",
"Name": "ST:131:0:{116d2292-e37d-41cd-a077-ebacac4c8cc4}"
},
{
"$type": "Bookmark",
"Name": "ST:0:0:{aa2115a1-9712-457b-9047-dbb71ca2cdd2}"
},
{
"$type": "Document",
"DocumentIndex": 0,
"Title": "ExcelHelper.csproj",
"DocumentMoniker": "D:\\code\\source\\repos\\ExcelHelper\\src\\ExcelHelper\\ExcelHelper.csproj",
"RelativeDocumentMoniker": "src\\ExcelHelper\\ExcelHelper.csproj",
"ToolTip": "D:\\code\\source\\repos\\ExcelHelper\\src\\ExcelHelper\\ExcelHelper.csproj",
"RelativeToolTip": "src\\ExcelHelper\\ExcelHelper.csproj",
"ViewState": "AgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
"Icon": "ae27a6b0-e345-4288-96df-5eaf394ee369.000758|",
"WhenOpened": "2025-02-28T01:19:10.825Z",
"EditorCaption": ""
}
]
}
]
}
]
}

View File

@ -0,0 +1 @@
{"ShowEmptyProjects":false,"CustomColumnOrderings":{"name":0,"file-path":1,"file-name":2,"neutral-value":3,"neutral-comment":4,"type":5},"ShowValidationErrors":true,"SelectedResourceGroupsByProject":{"D:\\code\\source\\repos\\ExcelHelper\\ExcelHelper.csproj":[]},"VisibleColumnKeys":["name","neutral-value","neutral-comment"]}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

3
.vs/ProjectSettings.json Normal file
View File

@ -0,0 +1,3 @@
{
"CurrentProjectSetting": null
}

View File

@ -0,0 +1,9 @@
{
"ExpandedNodes": [
"",
"\\src",
"\\src\\ExcelHelper"
],
"SelectedNode": "\\src\\ExcelHelper\\ExcelHelper.csproj",
"PreviewInSolutionExplorer": false
}

BIN
.vs/slnx.sqlite Normal file

Binary file not shown.

View File

@ -1,25 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35327.3
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExcelHelper", "ExcelHelper.csproj", "{C7A7E24D-513F-4D66-9953-42EDBD0038B7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C7A7E24D-513F-4D66-9953-42EDBD0038B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C7A7E24D-513F-4D66-9953-42EDBD0038B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C7A7E24D-513F-4D66-9953-42EDBD0038B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C7A7E24D-513F-4D66-9953-42EDBD0038B7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F92EF236-3F64-4327-8CF6-C6FDBDC7939E}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.13.35617.110 d17.13
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EleCho.MdViewer", "src\EleCho.MdViewer\EleCho.MdViewer.csproj", "{596C946D-6105-0155-6027-A60D28B5A46A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MdTest", "src\MdTest\MdTest.csproj", "{7774E67D-5655-66FF-EDE3-928AA28BA8DA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{596C946D-6105-0155-6027-A60D28B5A46A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{596C946D-6105-0155-6027-A60D28B5A46A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{596C946D-6105-0155-6027-A60D28B5A46A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{596C946D-6105-0155-6027-A60D28B5A46A}.Release|Any CPU.Build.0 = Release|Any CPU
{7774E67D-5655-66FF-EDE3-928AA28BA8DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7774E67D-5655-66FF-EDE3-928AA28BA8DA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7774E67D-5655-66FF-EDE3-928AA28BA8DA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7774E67D-5655-66FF-EDE3-928AA28BA8DA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2C42A4E7-8BE6-424F-BE4B-BD5B9206B8BD}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) [year] [fullname]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,34 @@
# EleCho.MdViewer
简易的WPF Markdown渲染器支持基础Markdown语法和深色模式。
> P.S. 该渲染器将Markdown文本渲染为ContentControl而非FlowDocument。
## 使用
1. 添加xmlns命名空间
```xml
xmlns:mu="clr-namespace:EleCho.MdViewer.Markup;assembly=EleCho.MdViewer"
xmlns:md="clr-namespace:EleCho.MdViewer;assembly=EleCho.MdViewer"
```
2. 添加模板样式和暗色/亮色模式配置
```xml
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<mu:ControlsDictionary />
<mu:ThemeDictionary ColorMode="Dark"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
```
3. 使用MdViewer控件
```xml
<ScrollViewer>
<md:MarkdownViewer x:Name="MdViewer"
Content="{Binding Markdown}"/>
</ScrollViewer>
```
## 定制主题
配置参考[/src/MdTest/CustomStyle.xaml](https://github.com/OrgEleCho/EleCho.MdViewer/blob/master/src/MdTest/CustomStyle.xaml)
在资源字典处替换```<mu:ThemeDictionary ColorMode="Dark"/>```即可。
## 示例
见测试项目[/src/MdTest](https://github.com/OrgEleCho/EleCho.MdViewer/tree/master/src/MdTest)
![light](https://raw.githubusercontent.com/OrgEleCho/EleCho.MdViewer/refs/heads/master/assets/example_light.png)
![dark](https://raw.githubusercontent.com/OrgEleCho/EleCho.MdViewer/refs/heads/master/assets/example_dark.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

View File

@ -0,0 +1,10 @@
namespace EleCho.MdViewer.ColorModes;
public enum ColorMode
{
Light, Dark
}
public static class ThemeColor
{
public static ColorMode ColorMode { get; set; }
}

View File

@ -0,0 +1,32 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:md="clr-namespace:EleCho.MdViewer.Markdown">
<Brush x:Key="{x:Static md:MarkdownResKey.MainForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.HeadingForeground}">#69f</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeBlockForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeBlockBackground}">#0CFFFFFF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeInlineForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeInlineBackground}">#8C6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.QuoteBlockForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.QuoteBlockBackground}">Transparent</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.QuoteBlockBorder}">#8C6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableBackground}">#0CFFFFFF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableStripe}">#0CFFFFFF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableBorder}">#3d3d3d</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.ThematicBreak}">#c5c5c5</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.Mark}">#8C6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.Link}">#9F6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.LinkHover}">#6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CommonControlMask}">#0CFFFFFF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CommonControlBorder}">#3d3d3d</Brush>
</ResourceDictionary>

View File

@ -0,0 +1,31 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:md="clr-namespace:EleCho.MdViewer.Markdown">
<Brush x:Key="{x:Static md:MarkdownResKey.MainForeground}">#1f2328</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.HeadingForeground}">#69f</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeBlockForeground}">#1f2328</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeBlockBackground}">#1C000000</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeInlineForeground}">#1f2328</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeInlineBackground}">#8C6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.QuoteBlockForeground}">#1f2328</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.QuoteBlockBackground}">Transparent</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.QuoteBlockBorder}">#8C6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableForeground}">#1f2328</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableBackground}">#e8e7e7</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableStripe}">#0C000000</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableBorder}">#dadada</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.ThematicBreak}">#c5c5c5</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.Mark}">#8C6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.Link}">#9F6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.LinkHover}">#6699FF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CommonControlMask}">#1C000000</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CommonControlBorder}">#dadada</Brush>
</ResourceDictionary>

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EleCho.MdViewer.Wrapper;
using System.Windows.Controls;
using System.Windows;
namespace EleCho.MdViewer.Controls;
public class SelectableTextBlock : TextBlock
{
static SelectableTextBlock()
{
FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));
TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);
// remove the focus rectangle around the control
FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));
}
private readonly TextEditorWrapper _editor;
public SelectableTextBlock()
{
_editor = TextEditorWrapper.CreateFor(this);
}
}

View File

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings>
<OutputType>Library</OutputType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ColorCode.Core" Version="2.0.15" />
<PackageReference Include="Markdig" Version="0.40.0" />
<PackageReference Include="WpfMath" Version="2.1.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,6 @@
namespace EleCho.MdViewer.Markdown;
public class MarkdownLinkNavigateEventArgs(string? link) : EventArgs
{
public string? Link { get; set; } = link;
}

View File

@ -0,0 +1,37 @@
namespace EleCho.MdViewer.Markdown;
public enum MarkdownResKey
{
MainForeground,
HeadingForeground,
CodeBlockBackground,
CodeBlockForeground,
CodeInlineForeground,
CodeInlineBackground,
QuoteBlockForeground,
QuoteBlockBackground,
QuoteBlockBorder,
TableForeground,
TableBackground,
TableStripe,
TableBorder,
ThematicBreak,
Mark,
Link,
LinkHover,
CommonControlMask,
CommonControlBorder
}
public enum ControlStyleKey
{
CheckBoxStyle,
HyperlinkStyle
}

View File

@ -0,0 +1,848 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using ColorCode.Styling;
using EleCho.MdViewer.ColorModes;
using EleCho.MdViewer.Controls;
using Markdig.Extensions.Mathematics;
using Markdig.Extensions.Tables;
using Markdig.Extensions.TaskLists;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using WpfDocs = System.Windows.Documents;
namespace EleCho.MdViewer.Markdown;
public class MarkdownWpfRenderer
{
public double Heading1Size = 24;
public double Heading2Size = 18;
public double Heading3Size = 16;
public double Heading4Size = 14;
public double NormalSize = 12;
public static event EventHandler<MarkdownLinkNavigateEventArgs>? LinkNavigate;
public FrameworkElement RenderDocument(MarkdownDocument document, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
if (document == null)
return new FrameworkElement();
StackPanel documentElement = new StackPanel();
foreach (var renderedBlock in RenderBlocks(document, cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
break;
documentElement.Children.Add(renderedBlock);
}
return documentElement;
}
public void RenderDocumentTo(ContentControl target, MarkdownDocument document, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return;
if (document == null)
return;
StackPanel documentElement = new StackPanel();
target.Content = documentElement;
foreach (var renderedBlock in RenderBlocks(document, cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
break;
documentElement.Children.Add(renderedBlock);
}
return;
}
public List<FrameworkElement> RenderBlocks(IEnumerable<Block> blocks, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new List<FrameworkElement>();
List<FrameworkElement> elements = new List<FrameworkElement>();
FrameworkElement? tailElement = null;
foreach (var block in blocks)
{
if (cancellationToken.IsCancellationRequested)
break;
FrameworkElement? renderedBlock = RenderBlock(block, cancellationToken);
if (renderedBlock != null)
{
elements.Add(renderedBlock);
tailElement = renderedBlock;
}
}
if (tailElement != null)
tailElement.Margin = tailElement.Margin with
{
Bottom = 0
};
return elements;
}
public FrameworkElement RenderBlock(Block block, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
if (block is ParagraphBlock paragraphBlock)
{
return RenderParagraphBlock(paragraphBlock, cancellationToken);
}
else if (block is HeadingBlock headingBlock)
{
return RenderHeadingBlock(headingBlock, cancellationToken);
}
else if (block is QuoteBlock quoteBlock)
{
return RenderQuoteBlock(quoteBlock, cancellationToken);
}
else if (block is FencedCodeBlock fencedCodeBlock)
{
if(fencedCodeBlock is MathBlock mathBlock)
{
return RenderMathBlock(mathBlock, cancellationToken);
}
else return RenderFencedCodeBlock(fencedCodeBlock, cancellationToken);
}
else if (block is CodeBlock codeBlock)
{
return RenderCodeBlock(codeBlock, cancellationToken);
}
else if (block is HtmlBlock htmlBlock)
{
return RenderHtmlBlock(htmlBlock, cancellationToken);
}
else if (block is ThematicBreakBlock thematicBreakBlock)
{
return RenderThematicBreakBlock(thematicBreakBlock, cancellationToken);
}
else if (block is ListBlock listBlock)
{
return RenderListBlock(listBlock, cancellationToken);
}
else if (block is Table table)
{
return RenderTable(table, cancellationToken);
}
else if (block is ContainerBlock containerBlock)
{
return RenderContainerBlock(containerBlock, cancellationToken);
}
else
{
return new TextBlock();
}
}
public FrameworkElement RenderContainerBlock(ContainerBlock containerBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
StackPanel documentElement = new StackPanel()
{
Margin = new Thickness(0, 0, 0, NormalSize)
};
foreach (var renderedBlock in RenderBlocks(containerBlock, cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
documentElement.Children.Add(renderedBlock);
}
return documentElement;
}
public FrameworkElement RenderTable(Table table, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
Border tableElement = new Border()
{
Margin = new Thickness(0, 0, 0, NormalSize),
CornerRadius=new CornerRadius(8),
HorizontalAlignment=HorizontalAlignment.Center
};
Grid tableContentElement = new Grid();
tableElement.Child = tableContentElement;
tableElement
.BindTableBackground();
foreach (var col in table.ColumnDefinitions)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
tableContentElement.ColumnDefinitions.Add(
new ColumnDefinition()
{
Width = GridLength.Auto
});
}
int rowIndex = 0;
foreach (var block in table)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
if (block is not TableRow row)
continue;
tableContentElement.RowDefinitions.Add(
new RowDefinition()
{
Height = GridLength.Auto
});
int colIndex = 0;
foreach (var colBlock in row)
{
if (colBlock is not TableCell cell)
continue;
Border cellElement = new Border()
{
Padding = new Thickness(NormalSize / 2, NormalSize / 4, NormalSize / 2, NormalSize / 4)
};
FrameworkElement cellContentElement =
RenderBlock(cell, cancellationToken);
cellElement.Child = cellContentElement;
cellElement
.BindTableBorder();
cellContentElement.Margin = new Thickness(4);
if (rowIndex % 2 == 1)
cellElement.BindTableStripe();
Grid.SetRow(cellElement, rowIndex);
Grid.SetColumn(cellElement, colIndex);
tableContentElement.Children.Add(cellElement);
colIndex++;
}
rowIndex++;
}
return tableElement;
}
public FrameworkElement RenderListBlock(ListBlock listBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
int itemCount = listBlock.Count;
Func<int, string> markerTextGetter = listBlock.IsOrdered ?
index => $"{index+1}." :
index => "•";
Border listElement = new Border()
{
Margin = new Thickness(NormalSize / 2, 0, 0, NormalSize)
};
Grid listContentElement = new Grid();
listElement.Child =
listContentElement;
listContentElement.ColumnDefinitions.Add(
new ColumnDefinition()
{
Width = GridLength.Auto,
});
listContentElement.ColumnDefinitions.Add(
new ColumnDefinition());
for (int i = 0; i < itemCount; i++)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
listContentElement.RowDefinitions.Add(
new RowDefinition()
{
Height = GridLength.Auto
});
}
int index = 0;
FrameworkElement? lastRenderedItemBlock = null;
foreach (var itemBlock in listBlock)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
if (RenderBlock(itemBlock, cancellationToken) is FrameworkElement renderedItemBlock)
{
lastRenderedItemBlock = renderedItemBlock;
renderedItemBlock.Margin = renderedItemBlock.Margin with
{
Bottom = renderedItemBlock.Margin.Bottom / 4
};
var marker = new SelectableTextBlock();
Grid.SetRow(marker, index);
Grid.SetColumn(marker, 0);
marker.Text = markerTextGetter.Invoke(index);
marker.Margin = new Thickness(0, 0, NormalSize / 2, 0);
marker.TextAlignment = TextAlignment.Right;
marker.BindMainForeground();
Grid.SetRow(renderedItemBlock, index);
Grid.SetColumn(renderedItemBlock, 1);
listContentElement.Children.Add(marker);
listContentElement.Children.Add(renderedItemBlock);
index++;
}
}
if (lastRenderedItemBlock != null)
lastRenderedItemBlock.Margin = lastRenderedItemBlock.Margin with
{
Bottom = 0
};
return listElement;
}
public FrameworkElement RenderThematicBreakBlock(ThematicBreakBlock thematicBreakBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
Border thematicBreakElement = new Border()
{
HorizontalAlignment = HorizontalAlignment.Stretch,
Height = 1,
Margin = new Thickness(0, 0, 0, NormalSize)
};
thematicBreakElement
.BindThematicBreak();
return thematicBreakElement;
}
public FrameworkElement RenderHtmlBlock(HtmlBlock htmlBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
var htmlText = new SelectableTextBlock();
htmlText.Text = htmlBlock.Lines.ToString();
return htmlText;
}
public FrameworkElement RenderMathBlock(MathBlock mathBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
string latex = mathBlock.Lines.ToString();
var math = new WpfMath.Controls.FormulaControl()
{
Formula = latex,
Scale = 20,
HorizontalAlignment=HorizontalAlignment.Center
};
math.SetResourceReference(Control.ForegroundProperty, MarkdownResKey.MainForeground);
var container = new Border()
{
Child = math
};
return container;
}
public FrameworkElement RenderFencedCodeBlock(FencedCodeBlock fencedCodeBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
if (string.IsNullOrWhiteSpace(fencedCodeBlock.Info))
return RenderCodeBlock(fencedCodeBlock, cancellationToken);
Border codeElement = new Border()
{
CornerRadius = new CornerRadius(8),
Margin = new Thickness(0, 0, 0, NormalSize)
};
var codeContentElement = new SelectableTextBlock()
{
TextWrapping = TextWrapping.Wrap,
Padding = new Thickness(NormalSize / 2),
FontSize = NormalSize,
FontFamily = GetCodeTextFontFamily(),
};
codeElement.Child =
codeContentElement;
codeElement.BindCodeBlockBackground();
codeContentElement.BindCodeBlockForeground();
var language = ColorCode.Languages.FindById(fencedCodeBlock.Info);
/*StyleDictionary styleDict = ColorMode switch
{
ColorMode.Light => StyleDictionary.DefaultLight,
ColorMode.Dark => StyleDictionary.DefaultDark,
_ => StyleDictionary.DefaultLight
};*/
StyleDictionary styleDict = StyleDictionary.DefaultDark;
WpfSyntaxHighLighting writer = new(styleDict);
writer.FormatTextBlock(fencedCodeBlock.Lines.ToString(), language, codeContentElement);
return codeElement;
}
public FrameworkElement RenderCodeBlock(CodeBlock codeBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
Border codeElement = new Border()
{
CornerRadius = new CornerRadius(8),
Margin = new Thickness(0, 0, 0, NormalSize)
};
var codeContentElement = new SelectableTextBlock()
{
TextWrapping = TextWrapping.Wrap,
Padding = new Thickness(NormalSize / 2),
FontSize = NormalSize,
FontFamily = GetCodeTextFontFamily(),
};
codeElement.Child =
codeContentElement;
codeElement
.BindCodeBlockBackground();
codeContentElement
.BindCodeBlockForeground();
if (codeBlock.Inline != null)
codeContentElement.Inlines.AddRange(
RenderInlines(codeBlock.Inline, cancellationToken));
codeContentElement.Inlines.Add(
new WpfDocs.Run(codeBlock.Lines.ToString()));
return codeElement;
}
public FrameworkElement RenderQuoteBlock(QuoteBlock quoteBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
Border quoteElement = new Border()
{
BorderThickness = new Thickness(NormalSize / 3, 0, 0, 0),
CornerRadius = new CornerRadius(NormalSize / 4),
Padding = new Thickness(NormalSize / 2, 0, 0, 0),
Margin = new Thickness(0, 0, 0, NormalSize),
};
StackPanel quoteContentPanel = new StackPanel();
quoteElement.Child =
quoteContentPanel;
quoteElement
.BindQuoteBlockBackground()
.BindQuoteBlockBorder();
foreach (var renderedBlock in RenderBlocks(quoteBlock, cancellationToken))
quoteContentPanel.Children.Add(renderedBlock);
return quoteElement;
}
public FrameworkElement RenderHeadingBlock(HeadingBlock headingBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
double fontSize = headingBlock.Level switch
{
1 => Heading1Size,
2 => Heading2Size,
3 => Heading3Size,
4 => Heading4Size,
_ => NormalSize
};
var headingElement = new SelectableTextBlock()
{
FontSize = fontSize,
FontWeight = FontWeights.Medium,
Margin = new Thickness(0, 0, 0, NormalSize)
};
headingElement
.BindHeadingForeground();
if (headingBlock.Inline != null)
headingElement.Inlines.AddRange(
RenderInlines(headingBlock.Inline, cancellationToken));
return headingElement;
}
public FrameworkElement RenderParagraphBlock(ParagraphBlock paragraphBlock, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new FrameworkElement();
SelectableTextBlock paragraphElement = new SelectableTextBlock()
{
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(0, 0, 0, NormalSize),
FontSize = NormalSize,
};
paragraphElement
.BindMainForeground();
if (paragraphBlock.Inline != null)
paragraphElement.Inlines.AddRange(
RenderInlines(paragraphBlock.Inline, cancellationToken));
return paragraphElement;
}
public List<WpfDocs.Inline> RenderInlines(IEnumerable<Inline> inlines, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new List<WpfDocs.Inline>();
List<WpfDocs.Inline> inlineElements = new List<WpfDocs.Inline>();
foreach (var inline in inlines)
if (RenderInline(inline, cancellationToken) is WpfDocs.Inline wpfInline)
{
if (cancellationToken.IsCancellationRequested)
break;
inlineElements.Add(wpfInline);
}
return inlineElements;
}
public WpfDocs.Inline RenderInline(Inline inline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
if (inline is LiteralInline literalInline)
{
return RenderLiteralInline(literalInline, cancellationToken);
}
else if (inline is LinkInline linkInline)
{
return RenderLinkInline(linkInline, cancellationToken);
}
else if (inline is LineBreakInline lineBreakInline)
{
return RenderLineBreakInline(lineBreakInline, cancellationToken);
}
else if (inline is HtmlInline htmlInline)
{
return RenderHtmlInline(htmlInline, cancellationToken);
}
else if (inline is HtmlEntityInline htmlEntityInline)
{
return RenderHtmlEntityInline(htmlEntityInline, cancellationToken);
}
else if (inline is EmphasisInline emphasisInline)
{
return RenderEmphasisInline(emphasisInline, cancellationToken);
}
else if (inline is CodeInline codeInline)
{
return RenderCodeInline(codeInline, cancellationToken);
}
else if (inline is AutolinkInline autolinkInline)
{
return RenderAutolinkInline(autolinkInline, cancellationToken);
}
else if (inline is DelimiterInline delimiterInline)
{
return RenderDelimiterInline(delimiterInline, cancellationToken);
}
else if (inline is ContainerInline containerInline)
{
return RenderContainerInline(containerInline, cancellationToken);
}
else if (inline is TaskList taskListInline)
{
return RenderTaskListInline(taskListInline, cancellationToken);
}
else if(inline is MathInline mathInline)
{
return RenderMathInline(mathInline, cancellationToken);
}
else
{
return new WpfDocs.Run();
}
}
public WpfDocs.Inline RenderMathInline(MathInline mathInline,CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
string latex = mathInline.Content.ToString();
var math = new WpfMath.Controls.FormulaControl()
{
Formula=latex,Scale=20
};
math.SetResourceReference(Control.ForegroundProperty, MarkdownResKey.MainForeground);
return math.WrapWithContainer();
}
public WpfDocs.Inline RenderTaskListInline(TaskList taskListInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
var box = new CheckBox()
{
IsChecked = taskListInline.Checked,
IsEnabled = false,
};
box.SetResourceReference(FrameworkElement.StyleProperty,ControlStyleKey.CheckBoxStyle);
return box.WrapWithContainer(); ;
}
public WpfDocs.Inline RenderAutolinkInline(AutolinkInline autolinkInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
return new WpfDocs.Run(autolinkInline.Url);
}
public WpfDocs.Inline RenderCodeInline(CodeInline codeInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
Border border = new Border()
{
CornerRadius = new CornerRadius(3),
Padding = new Thickness(NormalSize / 6, 0, NormalSize / 6, 0),
Margin = new Thickness(NormalSize / 6, 0, NormalSize / 6, 0)
};
TextBlock textBlock = new TextBlock();
border.Child = textBlock;
border
.BindCodeInlineBackground();
textBlock.Text = codeInline.Content;
return border.WrapWithContainer();
}
public WpfDocs.Inline RenderContainerInline(ContainerInline containerInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
WpfDocs.Span span = new WpfDocs.Span();
span.Inlines.AddRange(
RenderInlines(containerInline, cancellationToken));
return span;
}
public WpfDocs.Inline RenderEmphasisInline(EmphasisInline emphasisInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
WpfDocs.Span span = new WpfDocs.Span();
switch (emphasisInline.DelimiterChar)
{
case '*' when emphasisInline.DelimiterCount == 2: // bold
case '_' when emphasisInline.DelimiterCount == 2: // bold
span.FontWeight = FontWeights.Bold;
break;
case '*': // italic
case '_': // italic
span.FontStyle = FontStyles.Italic;
break;
case '~': // 2x strike through, 1x subscript
if (emphasisInline.DelimiterCount == 2)
span.TextDecorations.Add(TextDecorations.Strikethrough);
else
WpfDocs.Typography.SetVariants(span, FontVariants.Subscript);
break;
case '^': // 1x superscript
WpfDocs.Typography.SetVariants(span, FontVariants.Subscript);
break;
case '+': // 2x underline
span.TextDecorations.Add(TextDecorations.Underline);
break;
case '=': // 2x Marked
span.SetResourceReference(WpfDocs.Span.BackgroundProperty, MarkdownResKey.Mark);
break;
}
span.Inlines.AddRange(
RenderInlines(emphasisInline, cancellationToken));
return span;
}
public WpfDocs.Inline RenderHtmlEntityInline(HtmlEntityInline htmlEntityInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
return new WpfDocs.Run(htmlEntityInline.Transcoded.ToString());
}
public WpfDocs.Inline RenderHtmlInline(HtmlInline htmlInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
return new WpfDocs.Run();
}
public WpfDocs.Inline RenderLineBreakInline(LineBreakInline lineBreakInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
return new WpfDocs.Run("\n");
}
public WpfDocs.Inline RenderDelimiterInline(DelimiterInline delimiterInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
return new WpfDocs.Run(delimiterInline.ToLiteral());
}
public WpfDocs.Inline RenderLinkInline(LinkInline linkInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
Uri? uri = null;
if (linkInline.Url != null && Uri.TryCreate(linkInline.Url, UriKind.RelativeOrAbsolute, out Uri? _uri))
uri = _uri;
if (linkInline.IsImage)
{
Image img = new Image();
img.MaxWidth = 200;
if (uri != null)
img.Source = new BitmapImage(uri);
return img.WrapWithContainer();
}
else
{
WpfDocs.Hyperlink link = new();
link.SetResourceReference(FrameworkContentElement.StyleProperty, ControlStyleKey.HyperlinkStyle);
WpfDocs.Inline? linkContent = null;
if (linkInline.Label != null)
linkContent = new WpfDocs.Run(linkInline.Label);
if (linkContent != null)
link.Inlines.Add(linkContent);
if (RenderContainerInline(linkInline, cancellationToken) is WpfDocs.Inline extraInline)
link.Inlines.Add(extraInline);
link.Click += (s, e) =>
{
LinkNavigate?.Invoke(linkInline, new MarkdownLinkNavigateEventArgs(linkInline.Url));
};
return link;
}
}
public WpfDocs.Inline RenderLiteralInline(LiteralInline literalInline, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return new WpfDocs.Run();
return new WpfDocs.Run(literalInline.Content.ToString());
}
public FontFamily GetNormalTextFontFamily()
{
return new FontFamily("-apple-system,BlinkMacSystemFont,Segoe UI Adjusted,Segoe UI,Liberation Sans,sans-serif");
}
public FontFamily GetCodeTextFontFamily()
{
return new FontFamily("ui-monospace,Cascadia Code,Segoe UI Mono,Liberation Mono,Menlo,Monaco,Consolas,monospace");
}
}

View File

@ -0,0 +1,107 @@
using System.Windows;
using System.Windows.Controls;
using WpfDocs = System.Windows.Documents;
namespace EleCho.MdViewer.Markdown;
public static class MarkdownWpfRendererExtensions
{
public static TextBlock BindMainForeground(this TextBlock element)
{
element.SetResourceReference(TextBlock.ForegroundProperty, MarkdownResKey.MainForeground);
return element;
}
public static TextBlock BindHeadingForeground(this TextBlock element)
{
element.SetResourceReference(TextBlock.ForegroundProperty,MarkdownResKey.HeadingForeground);
return element;
}
public static TextBlock BindCodeBlockForeground(this TextBlock element)
{
element.SetResourceReference(TextBlock.ForegroundProperty, MarkdownResKey.CodeBlockForeground);
return element;
}
public static TextBox BindCodeBlockForeground(this TextBox element)
{
element.SetResourceReference(TextBox.ForegroundProperty, MarkdownResKey.CodeBlockForeground);
return element;
}
public static Border BindQuoteBlockBackground(this Border element)
{
element.SetResourceReference(Border.BackgroundProperty, MarkdownResKey.QuoteBlockBackground);
return element;
}
public static Border BindCodeBlockBackground(this Border element)
{
element.SetResourceReference(Border.BackgroundProperty, MarkdownResKey.CodeBlockBackground);
return element;
}
public static Border BindCodeInlineBackground(this Border element)
{
element.SetResourceReference(Border.BackgroundProperty, MarkdownResKey.CodeInlineBackground);
return element;
}
public static Border BindQuoteBlockBorder(this Border element)
{
element.SetResourceReference(Border.BorderBrushProperty, MarkdownResKey.QuoteBlockBorder);
return element;
}
public static TextBlock BindTableForeground(this TextBlock element)
{
element.SetResourceReference(TextBlock.ForegroundProperty, MarkdownResKey.TableForeground);
return element;
}
public static TextBlock BindTableBackground(this TextBlock element)
{
element.SetResourceReference(TextBlock.BackgroundProperty, MarkdownResKey.TableBackground);
return element;
}
public static Border BindTableBackground(this Border element)
{
element.SetResourceReference(Border.BackgroundProperty, MarkdownResKey.TableBackground);
return element;
}
public static Border BindTableStripe(this Border element)
{
element.SetResourceReference(Border.BackgroundProperty, MarkdownResKey.TableStripe);
return element;
}
public static Border BindTableBorder(this Border element)
{
element.SetResourceReference(Border.BorderBrushProperty, MarkdownResKey.TableBorder);
return element;
}
public static Border BindThematicBreak(this Border element)
{
element.SetResourceReference(Border.BackgroundProperty, MarkdownResKey.ThematicBreak);
return element;
}
public static WpfDocs.Inline WrapWithContainer(this UIElement element)
{
return new WpfDocs.Span()
{
BaselineAlignment = BaselineAlignment.Center,
Inlines =
{
new WpfDocs.InlineUIContainer()
{
Child = element
}
}
};
}
}

View File

@ -0,0 +1,144 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using ColorCode;
using ColorCode.Common;
using ColorCode.Parsing;
using ColorCode.Styling;
using WpfDocs = System.Windows.Documents;
namespace EleCho.MdViewer.Markdown;
public class WpfSyntaxHighLighting(StyleDictionary? Styles = null, ILanguageParser? languageParser = null) : CodeColorizerBase(Styles, languageParser)
{
private readonly static BrushConverter BrushConverter = new BrushConverter();
private InlineCollection? InlineCollection { get; set; }
public void FormatTextBlock(string sourceCode, ILanguage? language, TextBlock textBlock)
{
FormatInlines(sourceCode, language, textBlock.Inlines);
}
public void FormatInlines(string sourceCode, ILanguage? language, InlineCollection inlines)
{
this.InlineCollection = inlines;
if (language != null)
{
inlines.Add(new Run()
{
Text = language.Name+"\r\n",
FontSize = 10
});
languageParser.Parse(sourceCode, language, Write);
}
else
{
CreateSpan(sourceCode, null);
}
}
protected override void Write(string parsedSourceCode, IList<Scope> scopes)
{
var styleInsertions = new List<TextInsertion>();
foreach (Scope scope in scopes)
GetStyleInsertionsForCapturedStyle(scope, styleInsertions);
styleInsertions.SortStable((x, y) => x.Index.CompareTo(y.Index));
int offset = 0;
Scope? previousScope = null;
foreach (var styleinsertion in styleInsertions)
{
var text = parsedSourceCode.Substring(offset, styleinsertion.Index - offset);
CreateSpan(text, previousScope);
if (!string.IsNullOrWhiteSpace(styleinsertion.Text))
{
CreateSpan(text, previousScope);
}
offset = styleinsertion.Index;
previousScope = styleinsertion.Scope;
}
var remaining = parsedSourceCode.Substring(offset);
// Ensures that those loose carriages don't run away!
if (remaining != "\r")
{
CreateSpan(remaining, null);
}
}
private void CreateSpan(string text, Scope? scope)
{
var span = new Span();
var run = new Run
{
Text = text
};
// Styles and writes the text to the span.
if (scope != null)
StyleRun(run, scope);
span.Inlines.Add(run);
InlineCollection?.Add(span);
}
private void StyleRun(Run run, Scope scope)
{
string? foreground = null;
string? background = null;
bool italic = false;
bool bold = false;
if (Styles.Contains(scope.Name))
{
ColorCode.Styling.Style style = Styles[scope.Name];
foreground = style.Foreground;
background = style.Background;
italic = style.Italic;
bold = style.Bold;
}
if (!string.IsNullOrWhiteSpace(foreground))
{
try
{
run.Foreground = BrushConverter.ConvertFromString(foreground) as Brush;
}
catch { }
}
//Background isn't supported, but a workaround could be created.
if (italic)
run.FontStyle = FontStyles.Italic;
if (bold)
run.FontWeight = FontWeights.Bold;
}
private void GetStyleInsertionsForCapturedStyle(Scope scope, ICollection<TextInsertion> styleInsertions)
{
styleInsertions.Add(new TextInsertion
{
Index = scope.Index,
Scope = scope
});
foreach (Scope childScope in scope.Children)
GetStyleInsertionsForCapturedStyle(childScope, styleInsertions);
styleInsertions.Add(new TextInsertion
{
Index = scope.Index + scope.Length
});
}
}

View File

@ -0,0 +1,92 @@
using System.Windows;
using System.Windows.Controls;
using Markdig;
using Markdig.Syntax;
using EleCho.MdViewer.Markdown;
using System.Windows.Media.Media3D;
namespace EleCho.MdViewer;
public class MarkdownViewer : Control
{
private readonly MarkdownPipeline pipeline;
public MarkdownViewer()
{
pipeline = new MarkdownPipelineBuilder()
.UseEmphasisExtras()
.UseGridTables()
.UsePipeTables()
.UseTaskLists()
.UseAutoLinks()
.UseMathematics()
.Build();
}
static MarkdownViewer()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MarkdownViewer), new FrameworkPropertyMetadata(typeof(MarkdownViewer)));
}
public string Content
{
get { return (string)GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
public FrameworkElement RenderedContent
{
get { return (FrameworkElement)GetValue(RenderedContentProperty); }
private set { SetValue(RenderedContentProperty, value); }
}
public static readonly DependencyProperty ContentProperty =
DependencyProperty.Register(nameof(Content), typeof(string), typeof(MarkdownViewer), new PropertyMetadata(string.Empty, ContentChangedCallback));
public static readonly DependencyProperty RenderedContentProperty =
DependencyProperty.Register(nameof(RenderedContent), typeof(FrameworkElement), typeof(MarkdownViewer), new PropertyMetadata(null));
private async Task RenderProcessAsync(CancellationToken cancellationToken)
{
try
{
if (cancellationToken.IsCancellationRequested)
return;
string content = Content;
MarkdownDocument? doc =
await Task.Run(() =>
{
var doc = Markdig.Markdown.Parse(
content,
pipeline);
return doc;
});
var renderer = new MarkdownWpfRenderer();
ContentControl contentControl =new();
RenderedContent = contentControl;
renderer.RenderDocumentTo(contentControl, doc, cancellationToken);
}
catch { }
}
Task? renderProcessTask;
CancellationTokenSource? renderProcessCancellation;
private static void ContentChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not MarkdownViewer markdownViewer)
return;
if (markdownViewer.renderProcessCancellation is CancellationTokenSource cancellation)
cancellation.Cancel();
cancellation =
markdownViewer.renderProcessCancellation =
new CancellationTokenSource();
markdownViewer.renderProcessTask = markdownViewer.RenderProcessAsync(cancellation.Token);
}
}

View File

@ -0,0 +1,107 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mv="clr-namespace:EleCho.MdViewer"
xmlns:md="clr-namespace:EleCho.MdViewer.Markdown">
<Style TargetType="{x:Type mv:MarkdownViewer}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="mv:MarkdownViewer">
<ContentControl Content="{TemplateBinding RenderedContent}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="{x:Static md:ControlStyleKey.HyperlinkStyle}" TargetType="{x:Type Hyperlink}">
<Style.Triggers>
<Trigger Property="IsMouseOver"
Value="true">
<Setter Property="Foreground"
Value="{DynamicResource {x:Static md:MarkdownResKey.LinkHover}}" />
</Trigger>
<Trigger Property="IsEnabled"
Value="true">
<Setter Property="Cursor"
Value="Hand" />
</Trigger>
</Style.Triggers>
<Setter Property="Foreground"
Value="{DynamicResource {x:Static md:MarkdownResKey.Link}}" />
<Setter Property="TextDecorations"
Value="Underline" />
</Style>
<Style x:Key="{x:Static md:ControlStyleKey.CheckBoxStyle}"
TargetType="{x:Type CheckBox}">
<Setter Property="FocusVisualStyle"
Value="{x:Null}" />
<Setter Property="Background"
Value="{DynamicResource {x:Static md:MarkdownResKey.CommonControlMask}}" />
<Setter Property="BorderBrush"
Value="{DynamicResource {x:Static md:MarkdownResKey.CommonControlBorder}}" />
<Setter Property="Foreground"
Value="{DynamicResource {x:Static md:MarkdownResKey.MainForeground}}" />
<Setter Property="Padding"
Value="4 0 0 0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CheckBox}">
<Grid x:Name="templateRoot"
Background="Transparent"
SnapsToDevicePixels="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border x:Name="checkBoxBorder"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="1"
CornerRadius="4"
Margin="1"
Width="16"
Height="16">
<Grid x:Name="markGrid">
<Path x:Name="optionMark"
Data="F1 M 9.97498,1.22334L 4.6983,9.09834L 4.52164,9.09834L 0,5.19331L 1.27664,3.52165L 4.255,6.08833L 8.33331,1.52588e-005L 9.97498,1.22334 Z "
Fill="{TemplateBinding Foreground}"
Margin="3"
Opacity="0"
Stretch="Uniform" />
<Rectangle x:Name="indeterminateMark"
Fill="{TemplateBinding Foreground}"
Margin="2"
Opacity="0" />
</Grid>
</Border>
<ContentPresenter x:Name="contentPresenter"
Grid.Column="1"
Focusable="False"
HorizontalAlignment="Left"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True"
SnapsToDevicePixels="True"
VerticalAlignment="Center" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="HasContent"
Value="true">
<Setter Property="Padding"
Value="4,-1,0,0" />
</Trigger>
<Trigger Property="IsChecked"
Value="true">
<Setter Property="Opacity"
TargetName="optionMark"
Value="1" />
<Setter Property="Opacity"
TargetName="indeterminateMark"
Value="0" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

View File

@ -0,0 +1,17 @@
using System.Windows.Markup;
using System.Windows;
namespace EleCho.MdViewer.Markup;
[Localizability(LocalizationCategory.Ignore)]
[Ambient]
[UsableDuringInitialization(true)]
public class ControlsDictionary : ResourceDictionary
{
private const string DictionaryUri = "pack://application:,,,/EleCho.MdViewer;component/MarkdownViewer.xaml";
public ControlsDictionary()
{
Source = new Uri(DictionaryUri, UriKind.Absolute);
}
}

View File

@ -0,0 +1,28 @@
using System.Windows.Markup;
using System.Windows;
using EleCho.MdViewer.ColorModes;
namespace EleCho.MdViewer.Markup;
[Localizability(LocalizationCategory.Ignore)]
[Ambient]
[UsableDuringInitialization(true)]
public class ThemeDictionary : ResourceDictionary
{
private ColorMode _colorMode = ColorMode.Light;
public ColorMode ColorMode {
get => _colorMode;
set {
_colorMode = value;
UpdateColorMode();
}
}
public ThemeDictionary()
{
UpdateColorMode();
}
private void UpdateColorMode()
{
Source = new Uri($"pack://application:,,,/EleCho.MdViewer;component/ColorModes/{_colorMode}Mode.xaml", UriKind.Absolute);
}
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
namespace EleCho.MdViewer.Wrapper
{
class TextEditorWrapper
{
private static readonly Type TextEditorType = Type.GetType("System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
private static readonly PropertyInfo IsReadOnlyProp = TextEditorType.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly PropertyInfo TextViewProp = TextEditorType.GetProperty("TextView", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo RegisterMethod = TextEditorType.GetMethod("RegisterCommandHandlers",
BindingFlags.Static | BindingFlags.NonPublic, null, [typeof(Type), typeof(bool), typeof(bool), typeof(bool)], null);
private static readonly Type TextContainerType = Type.GetType("System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
private static readonly PropertyInfo TextContainerTextViewProp = TextContainerType.GetProperty("TextView");
private static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty("TextContainer", BindingFlags.Instance | BindingFlags.NonPublic);
public static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)
{
RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });
}
public static TextEditorWrapper CreateFor(TextBlock tb)
{
var textContainer = TextContainerProp.GetValue(tb);
var editor = new TextEditorWrapper(textContainer, tb, false);
IsReadOnlyProp.SetValue(editor._editor, true);
TextViewProp.SetValue(editor._editor, TextContainerTextViewProp.GetValue(textContainer));
return editor;
}
private readonly object _editor;
public TextEditorWrapper(object textContainer, FrameworkElement uiScope, bool isUndoEnabled)
{
_editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance,
null, new[] { textContainer, uiScope, isUndoEnabled }, null);
}
}
}

View File

@ -0,0 +1,15 @@
<Application x:Class="MdTest.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MdTest"
xmlns:mu="clr-namespace:EleCho.MdViewer.Markup;assembly=EleCho.MdViewer"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<mu:ControlsDictionary/>
<mu:ThemeDictionary ColorMode="Dark" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

View File

@ -0,0 +1,14 @@
using System.Configuration;
using System.Data;
using System.Windows;
namespace MdTest
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}

View File

@ -0,0 +1,10 @@
using System.Windows;
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]

View File

@ -0,0 +1,32 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:md="clr-namespace:EleCho.MdViewer.Markdown;assembly=EleCho.MdViewer">
<Brush x:Key="{x:Static md:MarkdownResKey.MainForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.HeadingForeground}">#8E44AD</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeBlockForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeBlockBackground}">#0CFFFFFF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeInlineForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CodeInlineBackground}">#8C8E44AD</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.QuoteBlockForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.QuoteBlockBackground}">Transparent</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.QuoteBlockBorder}">#8C8E44AD</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableForeground}">#dddddd</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableBackground}">#0CFFFFFF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableStripe}">#0CFFFFFF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.TableBorder}">#3d3d3d</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.ThematicBreak}">#c5c5c5</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.Mark}">#8C8E44AD</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.Link}">#9F8E44AD</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.LinkHover}">#8E44AD</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CommonControlMask}">#0CFFFFFF</Brush>
<Brush x:Key="{x:Static md:MarkdownResKey.CommonControlBorder}">#3d3d3d</Brush>
</ResourceDictionary>

View File

@ -0,0 +1,32 @@
<Window x:Class="MdTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MdTest"
xmlns:md="clr-namespace:EleCho.MdViewer;assembly=EleCho.MdViewer"
mc:Ignorable="d"
Title="MainWindow"
Background="#0E0E0E"
Height="450"
Width="800">
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<TextBox x:Name="MdEditor"
Grid.Column="0"
Background="#0E0E0E"
Foreground="#EFEFEF"
AcceptsReturn="True"
AcceptsTab="True"
TextWrapping="Wrap"
d:IsHidden="True" />
<ScrollViewer Grid.Column="1">
<md:MarkdownViewer x:Name="MdViewer"
Content="{Binding Text,ElementName=MdEditor}"
Margin="8" />
</ScrollViewer>
</Grid>
</Window>

View File

@ -0,0 +1,24 @@
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MdTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EleCho.MdViewer\EleCho.MdViewer.csproj" />
</ItemGroup>
</Project>

31
src/ExcelHelper.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.13.35818.85
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExcelHelper", "ExcelHelper\ExcelHelper.csproj", "{45C18155-32DF-EDC0-36CA-7E675D360F85}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EleCho.MdViewer", "EleCho.MdViewer\src\EleCho.MdViewer\EleCho.MdViewer.csproj", "{58E9A4B3-04CA-EF39-8DB9-923CD63AB1D3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{45C18155-32DF-EDC0-36CA-7E675D360F85}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{45C18155-32DF-EDC0-36CA-7E675D360F85}.Debug|Any CPU.Build.0 = Debug|Any CPU
{45C18155-32DF-EDC0-36CA-7E675D360F85}.Release|Any CPU.ActiveCfg = Release|Any CPU
{45C18155-32DF-EDC0-36CA-7E675D360F85}.Release|Any CPU.Build.0 = Release|Any CPU
{58E9A4B3-04CA-EF39-8DB9-923CD63AB1D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{58E9A4B3-04CA-EF39-8DB9-923CD63AB1D3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{58E9A4B3-04CA-EF39-8DB9-923CD63AB1D3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{58E9A4B3-04CA-EF39-8DB9-923CD63AB1D3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1D89A607-0616-468A-B3E3-0C04D3A604B6}
EndGlobalSection
EndGlobal

63
src/ExcelHelper/.gitattributes vendored Normal file
View File

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

363
src/ExcelHelper/.gitignore vendored Normal file
View File

@ -0,0 +1,363 @@
## 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
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# 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
nunit-*.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/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# 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
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# 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
# NuGet Symbol Packages
*.snupkg
# 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
*.appxbundle
*.appxupload
# 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
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# 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/
# 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/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

View File

@ -0,0 +1,74 @@
using System;
using System.ClientModel;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using OpenAI;
namespace ExcelHelper.AI;
class AiHelper
{
/// <summary>
/// 火山引擎
/// </summary>
private const string API_KEY = "58e5c6fd-a5da-400e-b889-715febce478f";
private const string API_ENDPOINT = "https://ark.cn-beijing.volces.com/api/v3/";
private readonly IChatClient _client;
private readonly bool UseTool = false;
public AiHelper(string modelName, bool useTools = false)
{
UseTool = useTools;
if (useTools)
{
//TODO: add function call
}
else
{
var client = new OpenAIClient(new ApiKeyCredential(API_KEY), new OpenAIClientOptions
{
Endpoint = new Uri(API_ENDPOINT),
});
_client = client.AsChatClient(modelName);
}
}
public IChatClient Client => _client;
public async Task<string> GetChatResponseAsync(string question)
{
var response = await _client.GetResponseAsync(question);
return response.Message.ToString();
}
public async IAsyncEnumerable<string> GetStreamingResponseAsync(string question)
{
// 获取所有的工具函数
//var toolsList = AgentExecutor.GetDefaultTools();
var chatOptions = new ChatOptions
{
// TODO: Models config
TopK= 10,
TopP = 0.85f,
Temperature = 0.7f,
};
if (UseTool)
{
//TODO: add function call
}
await foreach (var response in _client.GetStreamingResponseAsync(question, chatOptions))
{
yield return response.Text;
}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelHelper.AI
{
class PromptUtil
{
public static string UsePrompt(string msg,string excelPrompt)
{
return $@"
Excel公式大师Excel公式相关的问题
1.
2.
3. 2~3
4.
5. 使
{DateTime.Now}
excel文件列信息为{excelPrompt}
{msg}
";
}
}
}

View File

@ -2,13 +2,21 @@
x:Class="ExcelHelper.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ExcelHelper">
xmlns:local="clr-namespace:ExcelHelper"
xmlns:local1="clr-namespace:ExcelHelper.Converter"
xmlns:md="clr-namespace:EleCho.MdViewer;assembly=EleCho.MdViewer"
xmlns:mu="clr-namespace:EleCho.MdViewer.Markup;assembly=EleCho.MdViewer">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml" />
<ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml" />
<mu:ControlsDictionary />
<mu:ThemeDictionary ColorMode="Light" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>

View File

@ -0,0 +1,68 @@
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace ExcelHelper.Converter;
public class BoolToColorConverter : IValueConverter
{
public Brush UserMessageColor { get; set; } = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DCF8C6"));
public Brush AIMessageColor { get; set; } = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ECECEC"));
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool isUser)
{
return isUser ? UserMessageColor : AIMessageColor;
}
return AIMessageColor;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class BoolToAlignmentConverter : IValueConverter
{
public HorizontalAlignment TrueValue { get; set; } = HorizontalAlignment.Right;
public HorizontalAlignment FalseValue { get; set; } = HorizontalAlignment.Left;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool boolValue)
{
return boolValue ? TrueValue : FalseValue;
}
return FalseValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class InverseBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool boolValue)
{
return !boolValue;
}
return true;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool boolValue)
{
return !boolValue;
}
return true;
}
}

View File

@ -46,17 +46,22 @@
<ItemGroup>
<PackageReference Include="AvalonEdit" Version="6.3.0.90" />
<PackageReference Include="CommunityToolkit.Mvvm">
<Version>8.3.2</Version>
<Version>8.4.0</Version>
</PackageReference>
<PackageReference Include="DuckDB.NET.Bindings.Full" Version="1.1.3" />
<PackageReference Include="DuckDB.NET.Data.Full" Version="1.1.3" />
<PackageReference Include="HandyControl">
<Version>3.5.1</Version>
</PackageReference>
<PackageReference Include="MdXaml" Version="1.27.0" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Extensions.AI" Version="9.3.0-preview.1.25114.11" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="9.3.0-preview.1.25114.11" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3116-prerelease" />
<PackageReference Include="MiniExcel">
<Version>1.34.2</Version>
</PackageReference>
<PackageReference Include="Neo.Markdig.Xaml" Version="1.0.10" />
<PackageReference Include="PolySharp">
<Version>1.14.1</Version>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@ -69,4 +74,10 @@
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.0-rc.2.24473.5" />
<PackageReference Include="TinyPinyin" Version="1.1.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Web\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EleCho.MdViewer\src\EleCho.MdViewer\EleCho.MdViewer.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,129 @@
<UserControl
x:Class="ExcelHelper.Views.Components.AiMessageControll"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ExcelHelper.Views.Components"
xmlns:local1="clr-namespace:ExcelHelper.Converter"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:md="clr-namespace:EleCho.MdViewer;assembly=EleCho.MdViewer"
xmlns:mdxam="clr-namespace:MdXaml;assembly=MdXaml"
xmlns:mu="clr-namespace:EleCho.MdViewer.Markup;assembly=EleCho.MdViewer"
x:Name="userControl"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">
<UserControl.Resources>
<!-- 将布尔值转换为颜色 (用户消息和AI消息使用不同颜色) -->
<local1:BoolToColorConverter
x:Key="BoolToColorConverter"
AIMessageColor="#ECECEC"
UserMessageColor="#DCF8C6" />
<!-- 将布尔值转换为对齐方式 (用户消息靠右AI消息靠左) -->
<local1:BoolToAlignmentConverter
x:Key="BoolToAlignmentConverter"
FalseValue="Left"
TrueValue="Right" />
<!-- 布尔值取反转换器 -->
<local1:InverseBoolConverter x:Key="InverseBoolConverter" />
<!-- 布尔值到可见性转换器 -->
<BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter" />
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- 消息显示区 -->
<ScrollViewer
x:Name="MessageList"
Grid.Row="0"
Margin="5"
VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Messages, UpdateSourceTrigger=PropertyChanged, ElementName=userControl}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border
Margin="5"
Padding="5"
HorizontalAlignment="{Binding IsUser, Converter={StaticResource BoolToAlignmentConverter}}"
Background="{Binding IsUser, Converter={StaticResource BoolToColorConverter}}"
CornerRadius="10">
<StackPanel>
<md:MarkdownViewer x:Name="MdViewer" Content="{Binding Content}" />
<TextBlock
Margin="0,5,0,0"
HorizontalAlignment="Right"
FontSize="10"
Foreground="#99000000"
Text="{Binding Timestamp, StringFormat='{}{0:HH:mm}'}" />
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<!-- 输入区 -->
<Grid Grid.Row="1" Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Border
Grid.Column="0"
BorderBrush="#CCCCCC"
BorderThickness="1"
CornerRadius="5">
<TextBox
x:Name="MessageInput"
MinHeight="40"
MaxHeight="120"
Padding="8"
AcceptsReturn="True"
BorderThickness="0"
IsEnabled="{Binding IsWaiting, Converter={StaticResource InverseBoolConverter}, UpdateSourceTrigger=PropertyChanged, ElementName=userControl}"
KeyDown="MessageInput_KeyDown"
Text="{Binding CurrentMessage, UpdateSourceTrigger=PropertyChanged, ElementName=userControl}"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto" />
</Border>
<Button
Grid.Column="1"
Height="40"
Margin="5,0,0,0"
Padding="15,0"
Click="SendButton_Click"
Content="发送"
IsEnabled="{Binding IsWaiting, Converter={StaticResource InverseBoolConverter}, UpdateSourceTrigger=PropertyChanged, ElementName=userControl}" />
</Grid>
<!-- 等待指示器 -->
<Border
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2"
Background="#80FFFFFF"
Visibility="{Binding IsWaiting, Converter={StaticResource BoolToVisibilityConverter}, UpdateSourceTrigger=PropertyChanged, ElementName=userControl}">
<StackPanel
HorizontalAlignment="Center"
VerticalAlignment="Center"
Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="AI正在思考中..." />
<ProgressBar
Width="100"
Height="15"
Margin="10,0,0,0"
IsIndeterminate="True" />
</StackPanel>
</Border>
</Grid>
</UserControl>

View File

@ -0,0 +1,127 @@
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Media;
namespace ExcelHelper.Views.Components;
/// <summary>
/// AiMessageControll.xaml 的交互逻辑
/// </summary>
public partial class AiMessageControll : UserControl
{
// 消息集合
public ObservableCollection<ChatMessage> Messages
{
get => (ObservableCollection<ChatMessage>)GetValue(MessagesProperty);
set
{
SetValue(MessagesProperty, value);
ScrollToEnd();
}
}
public static readonly DependencyProperty MessagesProperty =
DependencyProperty.Register("Messages", typeof(ObservableCollection<ChatMessage>), typeof(AiMessageControll),
new PropertyMetadata(new ObservableCollection<ChatMessage>()));
// 当前输入的消息
public string CurrentMessage
{
get => (string)GetValue(CurrentMessageProperty);
set => SetValue(CurrentMessageProperty, value);
}
public static readonly DependencyProperty CurrentMessageProperty =
DependencyProperty.Register("CurrentMessage", typeof(string), typeof(AiMessageControll), new PropertyMetadata(string.Empty));
// 发送命令
public ICommand SendCommand
{
get => (ICommand)GetValue(SendCommandProperty);
set => SetValue(SendCommandProperty, value);
}
public static readonly DependencyProperty SendCommandProperty =
DependencyProperty.Register("SendCommand", typeof(ICommand), typeof(AiMessageControll), new PropertyMetadata(null));
// 是否正在等待AI响应
public bool IsWaiting
{
get => (bool)GetValue(IsWaitingProperty);
set => SetValue(IsWaitingProperty, value);
}
public static readonly DependencyProperty IsWaitingProperty =
DependencyProperty.Register("IsWaiting", typeof(bool), typeof(AiMessageControll), new PropertyMetadata(false));
public AiMessageControll()
{
InitializeComponent();
//DataContext = this;
}
private void SendButton_Click(object sender, RoutedEventArgs e)
{
if (SendCommand != null && SendCommand.CanExecute(CurrentMessage))
{
SendCommand.Execute(CurrentMessage);
}
}
private void MessageInput_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && !string.IsNullOrEmpty(CurrentMessage) && !IsWaiting)
{
if (SendCommand != null && SendCommand.CanExecute(CurrentMessage))
{
SendCommand.Execute(CurrentMessage);
}
e.Handled = true;
}
}
public void ScrollToEnd()
{
if (Messages.Count > 0)
{
MessageList.ScrollToEnd();
}
}
private void Markdownview_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
// 将滚动事件传递给外部的 ScrollViewer
var scrollViewer = FindParent<ScrollViewer>((DependencyObject)sender);
if (scrollViewer != null)
{
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta);
e.Handled = true;
}
}
private static T FindParent<T>(DependencyObject child) where T : DependencyObject
{
var parentObject = VisualTreeHelper.GetParent(child);
if (parentObject == null)
{
return null;
}
if (parentObject is T parent)
{
return parent;
}
else
{
return FindParent<T>(parentObject);
}
}
}

View File

@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using Markdig;
using Neo.Markdig.Xaml;
namespace ExcelHelper.Views.Components;
// 聊天消息类
public class ChatMessage : INotifyPropertyChanged
{
private string _content;
public string Content
{
get => _content;
set
{
_content = value;
OnPropertyChanged(nameof(Content));
//OnPropertyChanged(nameof(FlowDocument));
}
}
public FlowDocument FlowDocument
{
get
{
var doc = MarkdownXaml.ToFlowDocument(Content,
new MarkdownPipelineBuilder()
.UseXamlSupportedExtensions()
.Build()
);
return doc;
}
set => OnPropertyChanged(nameof(FlowDocument));
}
private bool _isUser;
public bool IsUser
{
get => _isUser;
set
{
_isUser = value;
OnPropertyChanged(nameof(IsUser));
}
}
private DateTime _timestamp = DateTime.Now;
public DateTime Timestamp
{
get => _timestamp;
set
{
_timestamp = value;
OnPropertyChanged(nameof(Timestamp));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

View File

@ -2,6 +2,7 @@
x:Class="ExcelHelper.Views.Pages.ImportExcelPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:components="clr-namespace:ExcelHelper.Views.Components"
xmlns:converter="clr-namespace:ExcelHelper.Converter"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hc="https://handyorg.github.io/handycontrol"
@ -52,6 +53,10 @@
Width="370"
MinWidth="370"
MaxWidth="600" />
<ColumnDefinition
Width="530"
MinWidth="530"
MaxWidth="600" />
</Grid.ColumnDefinitions>
<ContentPresenter
x:Name="DropFileMask"
@ -68,7 +73,7 @@
Panel.ZIndex="10"
Content="{Binding}"
ContentTemplate="{StaticResource LoadingMask}"
Visibility="{Binding IsLoading, Converter={StaticResource Boolean2VisibilityConverter}}" />
Visibility="{Binding IsLoading, Converter={StaticResource BooleanToVisibilityConverter}}" />
<hc:TabControl
Grid.Column="0"
Margin="5,5,7,5"
@ -202,6 +207,13 @@
</hc:SimpleStackPanel>
</hc:SimpleStackPanel>
</hc:Card>
<hc:Card Grid.Column="2">
<!-- Fix: Added Mode=OneWay -->
<components:AiMessageControll
CurrentMessage="{Binding CurrentMessage}"
IsWaiting="{Binding IsAiLoading}"
Messages="{Binding Messages}"
SendCommand="{Binding SendMessageToAiCommand}" />
</hc:Card>
</Grid>
</Page>

View File

@ -1,4 +1,4 @@
using System.Windows.Controls;
using System.Windows.Controls;
using CommunityToolkit.Mvvm.Messaging;
using ExcelHelper.Message;
using ExcelHelper.Views.ViewModels;
@ -73,4 +73,6 @@ public partial class ImportExcelPage : Page, IView, IRecipient<UpdateDataGridCol
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More