What would be the best approach to implement math formula rendering in a Cocoa application?
There is a utility app included with MacOS X called Grapher that do
If you only need to typeset equations and not build an interactive equation editor, you might want to look at using troff
. It's got a reasonably simple syntax for equations, outputs postscript, and is part of OS X. The easiest way to use it would also require ghostscript.
As an example (based on the man page):
Create the file file fib.tr
:
.EQ
x sub i = x sub {i-1} + x sub {i-2}
.EN
Convert to postscript with eqn
and groff
:
$ eqn fib.tr | groff -P-b16 > fib.ps
Calculate and extract the bounding box with ghostscript:
$ gs -dNOPAUSE -sDEVICE=bbox -- fib.ps 2> fib.bbox
Add the bounding box information to the ps file to generate an eps file:
$ cat fib.ps | sed -e '/%%Orientation/rfib.bbox' > fib.eps
Convert the eps file to a pdf using a perl script included with most TeX distributions (and available at http://tug.org/epstopdf/)
$ epstopdf fib.eps
Now you have a pdf image that contains just the rendered equation with minimal padding.
Alternatively, if your users have TeX installed (or you want to go through the hassle of bundling a minimal TeX distribution with your app), then LaTeXiT provides a service to typeset equations and return them as PDF images. You could call it using NSPerformService
.
As I describe in my answer to this similar question, I built a system for doing this in my iPhone application (which also works on the Mac, but I simply haven't completed that version of the application yet).
I used Core Animation layers to represent the hierarchy of the equation, with Quartz-drawn elements for the various operation types. This let me animate the typesetting in a relatively lightweight manner, which is smooth on even the first-generation iPhone hardware.
Like with the evaluation of arbitrary equations, splitting the layout into hierarchical layers makes the layout calculations pretty straightforward and flexible. However, it still took me months to get everything just right.
If you want to use an existing solution, you might look to Matt Gallagher's excellent open source project Magic Number Machine, which at least one developer has used as the basis for a commercial Mac calculator with equation typesetting.