JavaFX format Math during input - math

Is there a way that a mathematical expression can be formatted in JavaFX during input? Something like a TextArea that behaves exactly as the mathquill editor, which is for web applications?
If not, would it be possible to create a custom TextField / TextArea to provide such functionality? I have not yet looked into this so any guidance or suggestions are welcome :)
The only workaround I came up with is to input the expression as a String and convert it to an image using jLaTeXmath, which is not preferred as the end result should be an editable equation.
Short example on embedding jLaTeXmath:
This is done by converting a TeX expression to a BufferedImage that can be placed on a Pane. See below the code for the conversion:
/**
* Converts LaTeX code to a BufferedImage
* #param latex
*/
public static BufferedImage latexToImage(String latex){
String start ="\\begin{array}{l}";
start += latex;
start += "\\end{array}";
TeXFormula formula = new TeXFormula(start);
// Note: Old interface for creating icons:
//TeXIcon icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20);
// Note: New interface using builder pattern (inner class):
TeXIcon icon = formula.new TeXIconBuilder().setStyle(TeXConstants.STYLE_DISPLAY).setSize(65f).build();
icon.setInsets(new Insets(1, 1, 1, 1));
BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.setComposite(AlphaComposite.Clear);
// g2.setColor(Color.WHITE);
g2.fillRect(0,0,icon.getIconWidth(),icon.getIconHeight());
JLabel jl = new JLabel();
jl.setForeground(new Color(0, 0, 0));
g2.setComposite(AlphaComposite.Src);
icon.paintIcon(null, g2, 0, 0);
/*
File file = new File("Example2.png");
try {
ImageIO.write(image, "png", file.getAbsoluteFile());
} catch (IOException ex) {}
*/
return image;
}
The image can then be converted and set in a ImageView in JavaFX as folllows:
BufferedImage bimage = latexToImage("a = 2 \cdot x");
Image image = SwingFXUtils.toFXImage(bimage , null);
// have an ImageView in your scene and set the image
imgView.setImage(image );

The next coming versions of JavaFX support MathML by using a HTMLEditor Control :
JavaFX 8 Update 192 included in Java 8 Update 192
JavaFX 11.
Follow this link Java Early Access Download to reach the early access to these versions.
I'm afraid that what you are looking for doesn't exist yet.
There is a project in the JavaFX GitHub Reprository, but it's long term project.
About MathQuill, it seems that it is a JavaScript code. Or HTMLEditor uses an implementation of WebKit and can execute JavaScript code. It could be a short term solution.

Related

Allow user to copy data from TableView

I have a simple JavaFX app that allows the user to query a database and see the data in a table.
I'd like to allow the user to be able to click a table cell and copy text from that cell to the clipboard with the standard clipboard key stroke: ctrl-c for Win/Linux or cmd-c for Mac. FYI, the text entry controls support basic copy/paste by default.
I'm using the standard javafx.scene.control.TableView class. Is there a simple way to enable cell copy? I did some searches and I see other people create custom menu commands... I don't want to create a custom menu, I just want basic keyboard copy to work with single cells.
I'm using single selection mode, but I can change to something else if need be:
TableView<Document> tableView = new TableView<Document>();
tableView.getSelectionModel().setCellSelectionEnabled(true);
tableView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
You just have to create a listener in the scene, something like:
scene.getAccelerators()
.put(new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_ANY), new Runnable() {
#Override
public void run() {
int row = table.getSelectionModel().getSelectedIndex();
DataRow tmp = table.getItems().get(row);
final Clipboard clipboard = Clipboard.getSystemClipboard();
final ClipboardContent content = new ClipboardContent();
if(table.getSelectionModel().isSelected(row, numColumn)){
System.out.println(tmp.getNumSlices());
content.putString(tmp.getNumSlices().toString());
}
else{
System.out.println(tmp.getSelected());
content.putString(tmp.getSelected());
}
clipboard.setContent(content);
}
});
For a complete example, you can download it at the gist.
I recommended that you review this post, work for me
http://respostas.guj.com.br/47439-habilitar-copypaste-tableview-funcionando-duvida-editar-funcionalidade
The author use an aditional util java class for enable the cell content copy from a tableView

c# Tiff files compression methodology

I am trying to understand and implement a piece of code for Tiff compression.
I have already used 2 separate techniques - Using 3rd party dll's LibTiff.NEt (1st method is bulky) and the Image save method, http://msdn.microsoft.com/en-us/library/ytz20d80%28v=vs.110%29.aspx (2nd method works only on windows 7 machine but not on windows 2003 or 2008 server).
Now I am looking to explore this 3rd method.
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using System.Drawing.Imaging;
int width = 800;
int height = 1000;
int stride = width/8;
byte[] pixels = new byte[height*stride];
// Try creating a new image with a custom palette.
List<System.Windows.Media.Color> colors = new List<System.Windows.Media.Color>();
colors.Add(System.Windows.Media.Colors.Red);
colors.Add(System.Windows.Media.Colors.Blue);
colors.Add(System.Windows.Media.Colors.Green);
BitmapPalette myPalette = new BitmapPalette(colors);
// Creates a new empty image with the pre-defined palette
BitmapSource image = BitmapSource.Create(
width,
height,
96,
96,
System.Windows.Media.PixelFormats.BlackWhite,
myPalette,
pixels,
stride);
FileStream stream = new FileStream(Original_File, FileMode.Create);
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.Ccitt4;
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);
But I don't have a full understanding of what is happening here.
There is obviously some kind of a memory stream that the compression technique is being applied to. But I am a bit confused how to apply this to my specific case. I have an original tiff file, I want to use this method to set its compression to CCITT and save it back. Can anyone help?
I copied the above code and the code runs. But my end output file is a solid black background image. Although on the positive side it is of the correct compression type.
http://msdn.microsoft.com/en-us/library/ms616002%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.tiffcompressoption%28v=vs.100%29.aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/1585c562-f7a9-4cfd-9674-6855ffaa8653/parameter-is-not-valid-for-compressionccitt4-on-windows-server-2003-and-2008?forum=netfxbcl
LibTiff.net is a little bulky because it's based off LibTiff, which has its own set of problems.
My company (Atalasoft) has the ability to do that fairly easily, and the free version of the SDK will do the task you want with a few restrictions. The code for re-encoding a file would look like this:
public bool ReencodeFile(string path)
{
AtalaImage image = new AtalaImage(path);
if (image.PixelFormat == PixelFormat.Pixel1bppIndexed)
{
TiffEncoder encoder = new TiffEncoder();
encoder.Compression = TiffCompression.Group4FaxEncoding;
image.Save(path, encoder, null); // destroys the original - use carefully
return true;
}
return false;
}
Things you should be aware of:
this code will only work properly on 1bpp images
this code will NOT work properly on multi-page TIFFs
this code does NOT preserve metadata within the original file
and I would want the code to at least check for that. If you are inclined to have a solution that better preserves what's in the content of the file, you would want to do this:
public bool ReencodeFile(string origPath, string outputPath)
{
if (origPath == outputPath) throw new ArgumentException("outputPath needs to be different from input path.");
TiffDocument doc = new TiffDocuemnt(origPath);
bool needsReencoding = false;
for (int i=0; i < doc.Pages; i++) {
if (doc.Pages[i].PixelFormat == PixelFormat.Pixel1bppIndexed) {
doc.Pages[i] = new TiffPage(new AtalaImage(origPath, i, null), TiffCompression.Group4FaxEncoding);
needsReencoding = true;
}
}
if (needsReendcoding)
doc.Save(outputPath);
return needsReencoding;
}
This solution will respect all pages within the document as well as document metadata.

Annotation in pdfclown

I am trying to put a sticky note at some x,y location. For this i am using the pdfclown annotation class in .net.
Below is what is available.
using files = org.pdfclown.files;
public override bool Run()
{
files::File file = new files::File();
Document document = file.Document;
Populate(document);
Serialize(file, false, "Annotations", "inserting annotations");
return true;
}
private void Populate(Document document)
{
Page page = new Page(document);
document.Pages.Add(page);
PrimitiveComposer composer = new PrimitiveComposer(page);
StandardType1Font font = new StandardType1Font(document, StandardType1Font.FamilyEnum.Courier, true, false);
composer.SetFont(font, 12);
annotations::Note note = new annotations::Note(page, new Point(78, 658), "this is my annotation...");
note.IconType = annotations::Note.IconTypeEnum.Help;
note.ModificationDate = new DateTime();
note.IsOpen = true;
composer.Flush();
}
Link for annotation
This is putting a sticky note at 78, 658 cordinates in a blank pdf.
The problem is that i want that sticky note in a particular pdf which has some data. How can i modify it...thanks for the help..
I'm the author of PDF Clown -- this is the right way to insert an annotation like a sticky note into an existing page:
using org.pdfclown.documents;
using annotations = org.pdfclown.documents.interaction.annotations;
using files = org.pdfclown.files;
using System.Drawing;
. . .
// Open the PDF file!
using(files::File file = new files::File(#"C:\mypath\myfile.pdf"))
{
// Get the document (high-level representation of the PDF file)!
Document document = file.Document;
// Get, e.g., the first page of the document!
Page page = document.Pages[0];
// Insert your sticky note into the page!
annotations::Note note = new annotations::Note(page, new Point(78, 658), "this is my annotation...");
note.IconType = annotations::Note.IconTypeEnum.Help;
note.ModificationDate = new DateTime();
note.IsOpen = true;
// Save the PDF file!
file.Save(files::SerializationModeEnum.Incremental);
}
Please consider that there are lots of options about the way you can save your file (to an output (in-memory) stream, to a distinct path, as a compacted file, as an appended file...).
If you look at the 50+ samples accompanying the library's distribution, along with the API documentation, you can discover how expressive and powerful it is. Its architecture strictly adheres to the official Adobe PDF Reference 1.7.
enjoy!

How to use Tween for MovieClips in a Flex 4.5 application?

I'm new to Flex and am trying to port a pure Flash/AS3 card game to Flex 4.5.
It works mostly well, but I'm missing few puzzle parts there:
I've created a custom component based on UIComponent representing a deck of cards (which are an array of Sprites or MovieClips):
In the original pure Flash/AS3 game I was using Tween for the 3 cards at the table - to show the game user, who has put which card (by sliding them towards playing table middle):
import fl.transitions.*;
import fl.transitions.easing.*;
public class Deck extends UIComponent {
private var _card:Array = new Array(3);
private var _tween:Array = new Array(3);
....
override protected function createChildren():void {
_tween[YOU] = new Tween(_card[0], 'y', Regular.easeOut, _card[0].y + 40, _card[0].y, .5, true);
_tween[LEFT] = new Tween(_card[1], 'x', Regular.easeOut, _card[1].x - 40, _card[1].x, .5, true);
_tween[RIGHT] = new Tween(_card[2], 'x', Regular.easeOut, _card[2].x + 40, _card[2].x, .5, true);
....
However Flash Builder 4.5 doesn't seem to know fl.transitions.* packages at all?
Does anybody please have an advice on how to use Tween here?
Like I've written the rest (my custom Flex component, moving card-Sprites around, etc.) works well. Only the Tween lines had to be commented.
Thank you!
Alex
Take a look at the Tweener class on Google Code. With it you can specify and object, and a map of its properties and their desired values, along with time, and it will 'tween' those properties from their current to their desired values.
Tweener.addTween(yourCard, {y:50, time:1});//for a 1 second tween
My first knee-jerk reaction has been to add flash.swc (delivered by Flash CS Pro) to the Flex build path and then:
import fl.transitions.*;
import fl.transitions.easing.*;
can be used again.
But in the long-term I will probably write my own function to move the playing cards and run it on Event.ENTER_FRAME. Because I don't want to include Tweener or Tweenlite libraries for mere card sliding.
_tween[0] = _card[0].y;
_tween[1] = _card[1].x;
_tween[2] = _card[2].x;
....
_card[0].y = _tween[0] + 20;
addEventListener(Event.ENTER_FRAME, slideCardYou);
_card[1].x = _tween[1] - 20;
addEventListener(Event.ENTER_FRAME, slideCardLeft);
_card[2].x = _tween[2] + 20;
addEventListener(Event.ENTER_FRAME, slideCardRight);
....
private function slideCardYou(event:Event):void {
if (_card[0].y-- < _tween[0])
removeEventListener(Event.ENTER_FRAME, slideCardYou);
}
private function slideCardLeft(event:Event):void {
if (_card[1].x++ > _tween[1])
removeEventListener(Event.ENTER_FRAME, slideCardLeft);
}
private function slideCardRight(event:Event):void {
if (_card[2].x-- < _tween[2])
removeEventListener(Event.ENTER_FRAME, slideCardRight);
}
Also I've looked at mx.effects.Tween and spark.effects.Animate but they seem to be more appropriate for UIComponents and not Sprites as in my case.

AS3: reading embedded metadata in flex

I saw that you can embed meta-data into images very much like you can in mp3s, here.
Can someone point me to a tutorial of how to embed and read this sort of information w/ photoshop and flex together?
I really wouldn't know where to start... Tried googling but I'm not sure I have the right keywords down.
Thanks!
I've written a small snippet on the matter. this snippet is far from being proper tested, and is most definite not written in a clear and coherent way. But for now it seems to work. I'll update as I work on it.
private function init(event:Event):void
{
var ldr:Loader = new Loader();
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, imgLoaded);
var s:String = "link/to/asset.jpg";
ldr.load(new URLRequest(s));
}
private function imgLoaded(e:Event):void{
var info:LoaderInfo = e.target as LoaderInfo;
var xmpXML:XML = getXMP(info.bytes);
//trace(xmpXML);
var meta:XMPMeta = new XMPMeta(xmpXML);
}
private function trim(s:String):String{
return s.replace( /^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2" );
}
private function getXMP(ba:ByteArray):XML{
var LP:ByteArray = new ByteArray();
var PACKET:ByteArray = new ByteArray();
var l:int;
ba.readBytes(LP, 2, 2);
/*
http://www.adobe.com/devnet/xmp.html
read part 3: Storage in Files.
that will explain the -2 -29 and other things you see here.
*/
l = LP.readInt() - 2 -29;
ba.readBytes(PACKET, 33, l);
var p:String = trim(""+PACKET);
var i:int = p.search('<x:xmpmeta xmlns:x="adobe:ns:meta/"');
/* Delete all in front of the XMP XML */
p = p.substr(i);
/*
For some reason this left some rubbish in front, so I'll hardcode it out for now
TODO clean up
*/
var ar:Array = p.split('<');
var s:String = "";
var q:int;
var j:int = ar.length;
for(q=1;q<j;q++){
s += '<'+ar[q];
}
i = s.search('</x:xmpmeta>');
i += ('</x:xmpmeta>').length;
s = s.slice(0,i);
/* Delete all behind the XMP XML */
return XML(s);
}
Originally from http://snipplr.com/view/51037/xmp-metadata-from-jpg/
Photoshop (CS4+ I think) can also add XMP headers (XML style) which will be easier to parse than bytes but it contains different information.
http://code.google.com/p/exif-as3/
Here is a class that should do the job. It is non-commercial only but there is another option.
www.ultrashock.com/forums/server-side/extracting-metadata-from-photos-86065.html
Here is a php script that will do it that could be ported to as3 - it might be easier than creating one from scratch. If you did want php to read the info I would use the built in exif functions :)
Well AS3 don't have a built-in class to read jpg header.
BUT, if you are loading the image using URLLoader you can use the ByteArray to read if manually.
You can find the spec here:
http://www.obrador.com/essentialjpeg/HeaderInfo.htm
If you need some tutorial of using Bytearray you can start from here:
How to convert bytearray to image or image to bytearray ?
or here:
http://digitalmedia.oreilly.com/pub/a/oreilly/digitalmedia/helpcenter/flex3cookbook/chapter8.html?page=7
The principle is the same -read the bytes, convert them to readable data using the spec above and use it.
Good luck!
Yes, entirely possible. ByteArray is your friend.
You may want to give a read to this:
http://www.anttikupila.com/flash/getting-jpg-dimensions-with-as3-without-loading-the-entire-file/
This may also be of use, but I'd rather go with the first option:
http://download.macromedia.com/pub/developer/xmp/sdk/XMPLibrary-v1.0.zip

Resources