Giter VIP home page Giter VIP logo

xaml-math's Introduction

XAML-Math

XAML-Math is a collection of .NET libraries for rendering mathematical formulae using the LaTeX typesetting style, for the WPF and Avalonia XAML-based frameworks.

WPF-Math supports the following .NET variants:

  • .NET Framework 4.6.2 or later
  • .NET 6 or later

Avalonia-Math supports:

  • .NET Framework 4.6.2 or later
  • .NET Standard 2.0 or later
  • .NET 6 or later

A part of XAML-Math independent of the UI frameworks is published on NuGet as XAML-Math Shared Code: NuGet

Getting Started

The simplest way of using XAML-Math is to render a static formula in a XAML file as follows.

<!-- WPF -->
<Windowxmlns:controls="clr-namespace:WpfMath.Controls;assembly=WpfMath">
    <controls:FormulaControl Formula="\left(x^2 + 2 \cdot x + 2\right) = 0" />
</Window>

<!-- Avalonia -->
<Windowxmlns:controls="clr-namespace:AvaloniaMath.Controls;assembly=AvaloniaMath">
    <controls:FormulaBlock Formula="\left(x^2 + 2 \cdot x + 2\right) = 0" />
</Window>

For a more detailed sample, check out the example project. It shows the usage of data binding and some advanced concepts.

Screenshot of example project

Using the rendering API

The following example demonstrates usage of TexFormula API to render the image into a PNG file using the RenderToPng extension method:

using System;
using System.IO;
using WpfMath.Parsers;
using WpfMath;
using XamlMath.Exceptions;

namespace ConsoleApplication2
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            const string latex = @"\frac{2+2}{2}";
            const string fileName = @"T:\Temp\formula.png";

            try
            {
                var parser = WpfTeXFormulaParser.Instance;
                var formula = parser.Parse(latex);
                var pngBytes = formula.RenderToPng(20.0, 0.0, 0.0, "Arial");
                File.WriteAllBytes(fileName, pngBytes);
            }
            catch (TexException e)
            {
                Console.Error.WriteLine("Error when parsing formula: " + e.Message);
            }
        }
    }
}

Note that XamlMath.TexFormulaParser::Parse may throw a XamlMath.Exceptions.TexException if it was unable to parse a formula.

If you need any additional control over the image format, consider using the extension methods from the WpfTeXFormulaExtensions class:

using System;
using System.IO;
using System.Windows.Media.Imaging;
using WpfMath.Parsers;
using WpfMath.Rendering;
using XamlMath;

const string latex = @"\frac{2+2}{2}";
const string fileName = @"T:\Temp\formula.png";

var parser = WpfTeXFormulaParser.Instance;
var formula = parser.Parse(latex);
var environment = WpfTeXEnvironment.Create(TexStyle.Display, 20.0, "Arial");
var bitmapSource = formula.RenderToBitmap(environment);
Console.WriteLine($"Image width: {bitmapSource.Width}");
Console.WriteLine($"Image height: {bitmapSource.Height}");

var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
using (var target = new FileStream(fileName, FileMode.Create))
{
    encoder.Save(target);
    Console.WriteLine($"File saved to {fileName}");
}

You may also pass your own IElementRenderer implementation to TeXFormulaExtensions::RenderTo method if you need support for any alternate rendering engines.

Documentation

Build and Maintenance Instructions

Build the project using .NET SDK 7.0 or later. Here's the build and test script:

$ dotnet build XamlMath.All.sln --configuration Release
$ dotnet test XamlMath.All.sln

To approve the test results if they differ from the existing ones, execute the scripts/approve-all.ps1 script using PowerShell or PowerShell Core.

To publish the package, execute the following command:

$ dotnet pack XamlMath.All.sln --configuration Release

History

The library was originally ported from the JMathTex project, copyright 2004-2007 Universiteit Gent. The port was originally named WPF-TeX and was written and maintained by Alex Regueiro. It was later available as WPF-Math on Launchpad, but was unmaintained from 2011 until it 2017, when was revived in its current form.

In 2023, after adding the Avalonia support, the WPF-Math project was renamed to XAML-Math.

License Notes

The project code and all the resources are distributed under the terms of MIT license.

The fonts cmex10.ttf, cmmi10.ttf, cmr10.ttf, and cmsy10.ttf and cmtt10.ttf are under the Knuth License.

The font file jlm_msam10.ttf (taken from JLaTeXMath project) is licensed under the Open Font License.

XAML-Math (named WPF-Math at the time) started as a direct port of JMathTeX project written in Java, reusing both code and resources. JMathTeX is distributed under the terms of GNU GPL v2 license. XAML-Math, being a derived work, has a permission from JMathTeX authors to be redistributed under the MIT license. See the Licensing history for the details.

We're very grateful to JMathTeX authors for their work and allowing to redistribute the derived library. JMathTeX is written by:

  • Kris Coolsaet
  • Nico Van Cleemput
  • Kurt Vermeulen

xaml-math's People

Contributors

ahopper avatar alexreg avatar b3zaleel avatar dependabot[bot] avatar fornever avatar gregorymorse avatar gsomix avatar hez2010 avatar hugmouse avatar kolosovpetro avatar lehonti avatar lellid avatar nevgeny avatar nikolaisviridov avatar orace avatar rennmaus-coder avatar rstm-sf avatar sskodje avatar theoneamir avatar thor181 avatar yamamoto-reki avatar ygra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xaml-math's Issues

Cannot change text style

We have \mathrm, \mathit, \mathcal command, but it doesn't affect on rendering.

We should fix it first, before implementing #32 as math functions (sin, cos, log) have \mathrm style.

Publish to NuGet

I want the package to be published to NuGet. I don't think we need .NET 3.5 version, but 4.0 should be available.

Add \text{} command

Reported by our user in #82 (comment): \text{abc} doesn't work; it says "Unknown symbol or command or predefined TeXFormula: 'text'".

I've confirmed that \text{} command never worked in any released version, so that's not a regression but a lack of feature.

Merge patches from the old repository

There's a bunch of patches attached to the old repository tracker. I think it should be worth to check them out and apply to our codebase.

Ideally we should treat these patches as our own pull requests: we should try our best to reproduce the mentioned issues (probably even write the unit tests), and merge the changes afterwards. The maintainer on duty (well, probably myself) should notify the patch authors that the patches are being merged here.

Add parser tests

My general experience about parsing dictates one simple rule: every parser should have a set of unit tests. Parsers are usually very complex beasts, but it's not that hard to test them: you just pass in some text sequences and compare parser output with stuff you expect.

I think that we'll add unit tests (and will set up CI to execute them) in #14.

Exceptions while starting example

There are a lot of similar exceptions at start.

Exception thrown: 'System.Collections.Generic.KeyNotFoundException' in mscorlib.dll
Exception thrown: 'WpfMath.FormulaNotFoundException' in WpfMath.dll

Add control with inline math rendering capabilities

Current custom control would be cumbersome to use to produce paragraphs of text with inline math or longer flowing text with math as separate lines. See example below

http://marked2app.com/help/images/mathjax2.jpg

A control based on, e.g., a textbox, but with added handles such as [$, $] that uses the renderer would be a very useful addition.

EDIT

Did some research on this. Perhaps a using BlockUIContainer and InlineUIContainer inside a FlowDocument is a better way to go.

\overline command

Hello!

Please implement \overline. This command doesn't work now.

Thanks.

Nuget version does not include Controls namespace

Hi, I found WpfMath available as a nuget package in VS2015. Although it claims to be v0.2 the whole namespace WpfMath.Controls is missing there, thus making it useless for usage as a WPF control.

Would be great to just reference the nuget package except the need to build my own version from the sources.

Documentation about dealing with XML

I want to generate DefaultTexFont.xml from the TTF files we have.

Comments from jlatexmath maintainer were helpful, but I'm still struggling with that. Will document after I find everything out.

NuGet package restore failed in Visual Studio

When building the project in Visual Studio 2015, I got this:

3>wpf-math\src\WpfMath.Tests\WpfMath.Tests.fsproj(102,5): error : This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\xunit.runner.visualstudio.2.2.0\build\net20\xunit.runner.visualstudio.props.

It likely was broken by commit e67bc2a. Need to investigate.

Support UTF8

Can you support UTF8 symbols? I can't add symbols from other languages than English!

Replace XML files with something else

We have a bunch of XML files, namely:

  • DefaultTexFont.xml
  • GlueSettings.xml
  • PredefinedTexFormulas.xml
  • TexFormulaSettings.xml
  • TexSymbols.xml

There's a consensus between current contributors that we need to replace them with something else.

I think that PredefinedTexFormulas, GlueSettings, TexFormulaSettings and TexSymbols can be completely replaced by code without problems.

DefaultTexFont is a bit different, because it would be too much code to replace it. I'd like to research if we can extract some of its information from the font files we provide. Probably these mappings were originally created by some script we could find and/or rewrite.

After all of the files are gone, we could remove GPL license and release a new version with MIT exclusively.

Extensible delimiters (\left and \right)

Full brace list we need to support:

  • \left. \right. (empty delimiter)
  • \left( \right)
  • \left[ \right]
  • \left\{ \right\}
  • \left< \right>
  • \left| \right|

Plan

  • take a look at Java implementation — at least JLatexMath seems to support those delimiters ~ F
  • implement delimiters as a resizable characters (i.e. don't split them into top / top-middle / etc. parts yet)
  • add full support with splitting the characters into parts — it suddenly turned out that we already have those

Macro support in PredefinedTexFormulas.xml

To reduce boilerplate like this, I'd like to introduce simple macro support into TexPredefinedFormulaParser. These should become simply like

<ApplyMacro name="simpleFunction"><MacroArgument value="sin" /></ApplyMacro>
<ApplyMacro name="simpleFunction"><MacroArgument value="cos" /></ApplyMacro>

so on.

(With simpleFunction macro defined in the same file, of course.)

Bar alignment

In my statistical application I need to show a double bar over one character like in image

doublebarx

I try the syntax \bar{\bar{X}} but the bars are not aligned

alignbar

Replace parser with MathTeX.NET one

A better parser infrastructure for TeX syntax already exists in the MathTeX.NET project, which I worked on around the same time as the original version of WPF-Math. I don't mind using an alternative, but I do think we should refactor the parsing code into a proper, extensible project in another project, and have the core layout/rendering library only take an AST (abstract syntax tree) as input. That way we can then add other input syntaxes in a nice way (e.g. MathML). Of course, the rendering will later be split off from the core library too, but that can come later.

Improve blurred output

Hi,
Currently formulas are rendered pretty blurred.

Toying with the v0.3 version now it seems I'm unable to influence the rendering of the formula with any of the usual options, RenderOptions, TextOptions, UseLayoutRounding. I tried basically all combinations but to no avail. Can you give any hint on how to reduce the blur?

Btw, thx for the lightning speed in releasing v0.3 👍

Extensible definition dictionary

To avoid polluting our main formula dictionary (i.e. PredefinedTexFormulas.xml) with various localized formula names (like this), I propose to add a dictionary extension mechanism.

Users should be able to provide theirs own dictionary files that will be merged with the existing definitions.

Also, these Russian localized definitions should be extracted from the default dictionary and should became opt-in functionality (I still want to redistribute them alongside WPF-Math because personally I need those, and I think they're generally useful for people around the world).

And don't forget to add end-user documentation explaining how to make and apply these definition files!

Project setup

  • Standartize Readme and License
  • Merge Authors.txt together with the project history into the Readme
  • Clean up the sources, setup .gitignore

Problem with Cyrillic

Suppose I want to render LaTeX formula including Cyrillic characters: ЭЭ_E = t \cdot ПДУ. WPF-Math should fall back to the default font or (preferably) allow the user to specify fallback, and it should actually render the text.

Texpaste allows this, for example (and it looks like it uses system-default fallback):
image

Currently WPF-Math fails with the "Unknown character" error on this formula.

Rich error messages

We should to revise all parser error messages and make them more concise and rich. E.g. add info about index of symbol where error was occured.

Some more project tags

Suggestions to add: dotnet, csharp, tex, mathematics, math/maths, rendering, graphics (include which ones you will)

Get official

I'd like the people from the outdated launchpad page to be aware about this resurrection of the original project. For that, I'd like the project description on Launchpad to include a link to GitHub.

To change the Launchpad description, I'd like to cooperate with the original project developer, @alexreg.

@alexreg, Alexander, hello and huge big thank you for your work on the original project! Could you please edit the project description on the Launchpad page?

I'm sort of library archaeologist, and I'm going to maintain the library fork, making it available on the new platforms and generally patch it the best I can.

Avalonia support

Avalonia

TODO

  • create a branch for Avalonia stuff (and we will then proceed to work on that branch using PRs with the usual branching policy, almost as with the master): feature/17-avalonia
  • make PR #98 non-destructive (because currently it destroys stuff, and that's unwanted) and merge it into the branch
  • fix builds and add CI support for both modes (WPF and Avalonia)
  • rebase work of @ahopper from #170 on top of the branch
  • make sure tests work for WPF part
  • make FormulaBlock public
  • solve #63 in the branch
  • remove the code duplication (at least most of it) — that's why #63 was necessary
  • update the documentation
  • after all of that, Avalonia may land into the master branch
  • add packaging for Avalonia, but explicitly mark the packages as alpha (#192)
  • check issue #128: it should'nt be reproducible for WPF and for Avalonia
  • currently we're planning to only allow for solid colors in the portable code base; we'll have to think about supporting for non-solid colors (aka Brushes) for WPF- and Avalonia-dependent code
  • Make sure the resources (.xml and .ttf) are deduplicated properly.

MathML input

It might be nice to add support for MathML parsing as an alternative to TeX input. Just a thought. This is certainly not a priority, in my mind.

Explicate copyright permission of jmathtex

While the copyright statement on the readme.md notes that the files from the JMathTeX project are licensed in MIT, this repository does not contain the permission notice.

I ask about this matter here.

Could you please add a communication trace of this permission to this repository, or a link to this permission? Our corporate overlords may then accept use of this library. Lots of thanks in advance!

Clarify font licensing

We're currently providing some TTF files, but I can't find their license (it'd be unusual to find that the fonts are licensed by GPL, too). Some of them looks like Computer Modern (which is distributed under something marked as "Knuth license"). We need to find the source and properly attribute these files.

Please implement array

It seems that array is not supported. Following expression does not work.
\left[\begin{array}1 & 2 & 3 & 4 & 5 \3 & 4 & 5 & 6 & 7 \end{array}\right]

Add formula control to the library

As a library user, I want to have a WPF control that'll be able to render the formula. Usage should be like that:

<FormulaControl Formula="E = m \cdot c ^ 2"/> <!-- Simple text formula -->
<FormulaControl Formula="{Binding SomeMath}" /> <!-- With binding -->

That control should be included into the library and published to NuGet.

Add mathematical functions

I have the feature request from Russian F# StackOverflow chat: add arctg and arcctg functions. I think that's time to review the functions we have and add those trigonometric functions we still haven't.

Please note that the ordinary notation for tangent is tan, but tg is also a common extension I think.

Probably these should go into PredefinedTexFormulas.xml.

Command arguments passed without braces

Currently \frac22 fails with an error "missing {" although it actually should render as this:

image

I suggest we take actual EBNF for LaTeX and implement that instead of relying on intuition :)

Differential operators

What do you think if we add common differential operators like \grad, \div, \rot (\curl)? The only problem I see it's collision between \div (÷) symbol and divergence operator. But division symbol is rarely used, I think we can redefine it as \divsymb [1].

[1] See \div operator: http://www.dfcd.net/articles/latex/latex.html

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.