repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/image4j/BMPConstants.java
released/MyBox/src/main/java/thridparty/image4j/BMPConstants.java
/* * BMPConstants.java * * Created on 10 May 2006, 08:17 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; /** * Provides constants used with BMP format. * * @author Ian McDonagh */ public class BMPConstants { private BMPConstants() { } /** * The signature for the BMP format header "BM". */ public static final String FILE_HEADER = "BM"; /** * Specifies no compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_RGB = 0; // no compression /** * Specifies 8-bit RLE compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_RLE8 = 1; // 8bit RLE compression /** * Specifies 4-bit RLE compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_RLE4 = 2; // 4bit RLE compression /** * Specifies 16-bit or 32-bit "bit field" compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_BITFIELDS = 3; // 16bit or 32bit "bit field" // compression. /** * Specifies JPEG compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_JPEG = 4; // _JPEG compression /** * Specifies PNG compression. * * @see InfoHeader#iCompression InfoHeader */ public static final int BI_PNG = 5; // PNG compression }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/image4j/ICOConstants.java
released/MyBox/src/main/java/thridparty/image4j/ICOConstants.java
/* * ICOConstants.java * * Created on May 13, 2006, 8:07 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; /** * Provides constants used with ICO format. * @author Ian McDonagh */ public class ICOConstants { /** * Indicates that ICO data represents an icon (.ICO). */ public static final int TYPE_ICON = 1; /** * Indicates that ICO data represents a cursor (.CUR). */ public static final int TYPE_CURSOR = 2; }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/image4j/BMPDecoder.java
released/MyBox/src/main/java/thridparty/image4j/BMPDecoder.java
/* * Decodes a BMP image from an <tt>InputStream</tt> to a <tt>BufferedImage</tt> * * @author Ian McDonagh */ package thridparty.image4j; import java.awt.image.*; import java.io.*; /** * Decodes images in BMP format. * @author Ian McDonagh */ public class BMPDecoder { private BufferedImage img; private InfoHeader infoHeader; /** Creates a new instance of BMPDecoder and reads the BMP data from the source. * @param in the source <tt>InputStream</tt> from which to read the BMP data * @throws java.io.IOException if an error occurs */ public BMPDecoder(java.io.InputStream in) throws IOException { LittleEndianInputStream lis = new LittleEndianInputStream(new CountingInputStream(in)); /* header [14] */ //signature "BM" [2] byte[] bsignature = new byte[2]; lis.read(bsignature); String signature = new String(bsignature, "UTF-8"); if (!signature.equals("BM")) { throw new IOException("Invalid signature '"+signature+"' for BMP format"); } //file size [4] int fileSize = lis.readIntLE(); //reserved = 0 [4] int reserved = lis.readIntLE(); //DataOffset [4] file offset to raster data int dataOffset = lis.readIntLE(); /* info header [40] */ infoHeader = readInfoHeader(lis); /* Color table and Raster data */ img = read(infoHeader, lis); } /** * Retrieves a bit from the lowest order byte of the given integer. * @param bits the source integer, treated as an unsigned byte * @param index the index of the bit to retrieve, which must be in the range <tt>0..7</tt>. * @return the bit at the specified index, which will be either <tt>0</tt> or <tt>1</tt>. */ private static int getBit(int bits, int index) { return (bits >> (7 - index)) & 1; } /** * Retrieves a nibble (4 bits) from the lowest order byte of the given integer. * @param nibbles the source integer, treated as an unsigned byte * @param index the index of the nibble to retrieve, which must be in the range <tt>0..1</tt>. * @return the nibble at the specified index, as an unsigned byte. */ private static int getNibble(int nibbles, int index) { return (nibbles >> (4 * (1 - index))) & 0xF; } /** * The <tt>InfoHeader</tt> structure, which provides information about the BMP data. * @return the <tt>InfoHeader</tt> structure that was read from the source data when this <tt>BMPDecoder</tt> * was created. */ public InfoHeader getInfoHeader() { return infoHeader; } /** * The decoded image read from the source input. * @return the <tt>BufferedImage</tt> representing the BMP image. */ public BufferedImage getBufferedImage() { return img; } private static void getColorTable(ColorEntry[] colorTable, byte[] ar, byte[] ag, byte[] ab) { for (int i = 0; i < colorTable.length; i++) { ar[i] = (byte) colorTable[i].bRed; ag[i] = (byte) colorTable[i].bGreen; ab[i] = (byte) colorTable[i].bBlue; } } /** * Reads the BMP info header structure from the given <tt>InputStream</tt>. * @param lis the <tt>InputStream</tt> to read * @return the <tt>InfoHeader</tt> structure * @throws java.io.IOException if an error occurred */ public static InfoHeader readInfoHeader(thridparty.image4j.LittleEndianInputStream lis) throws IOException { InfoHeader infoHeader = new InfoHeader(lis); return infoHeader; } /** * @since 0.6 */ public static InfoHeader readInfoHeader(thridparty.image4j.LittleEndianInputStream lis, int infoSize) throws IOException { InfoHeader infoHeader = new InfoHeader(lis, infoSize); return infoHeader; } /** * Reads the BMP data from the given <tt>InputStream</tt> using the information * contained in the <tt>InfoHeader</tt>. * @param lis the source input * @param infoHeader an <tt>InfoHeader</tt> that was read by a call to * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()}. * @return the decoded image read from the source input * @throws java.io.IOException if an error occurs */ public static BufferedImage read(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis) throws IOException { BufferedImage img = null; /* Color table (palette) */ ColorEntry[] colorTable = null; //color table is only present for 1, 4 or 8 bit (indexed) images if (infoHeader.sBitCount <= 8) { colorTable = readColorTable(infoHeader, lis); } img = read(infoHeader, lis, colorTable); return img; } /** * Reads the BMP data from the given <tt>InputStream</tt> using the information * contained in the <tt>InfoHeader</tt>. * @param colorTable <tt>ColorEntry</tt> array containing palette * @param infoHeader an <tt>InfoHeader</tt> that was read by a call to * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()}. * @param lis the source input * @return the decoded image read from the source input * @throws java.io.IOException if any error occurs */ public static BufferedImage read(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis, ColorEntry[] colorTable) throws IOException { BufferedImage img = null; //1-bit (monochrome) uncompressed if (infoHeader.sBitCount == 1 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read1(infoHeader, lis, colorTable); } //4-bit uncompressed else if (infoHeader.sBitCount == 4 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read4(infoHeader, lis, colorTable); } //8-bit uncompressed else if (infoHeader.sBitCount == 8 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read8(infoHeader, lis, colorTable); } //24-bit uncompressed else if (infoHeader.sBitCount == 24 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read24(infoHeader, lis); } //32bit uncompressed else if (infoHeader.sBitCount == 32 && infoHeader.iCompression == BMPConstants.BI_RGB) { img = read32(infoHeader, lis); } else { throw new IOException("Unrecognized bitmap format: bit count="+infoHeader.sBitCount+", compression="+ infoHeader.iCompression); } return img; } /** * Reads the <tt>ColorEntry</tt> table from the given <tt>InputStream</tt> using * the information contained in the given <tt>infoHeader</tt>. * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @param lis the <tt>InputStream</tt> to read * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static ColorEntry[] readColorTable(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis) throws IOException { ColorEntry[] colorTable = new ColorEntry[infoHeader.iNumColors]; for (int i = 0; i < infoHeader.iNumColors; i++) { ColorEntry ce = new ColorEntry(lis); colorTable[i] = ce; } return colorTable; } /** * Reads 1-bit uncompressed bitmap raster data, which may be monochrome depending on the * palette entries in <tt>colorTable</tt>. * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @param lis the source input * @param colorTable <tt>ColorEntry</tt> array specifying the palette, which * must not be <tt>null</tt>. * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read1(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis, ColorEntry[] colorTable) throws IOException { //1 bit per pixel or 8 pixels per byte //each pixel specifies the palette index byte[] ar = new byte[colorTable.length]; byte[] ag = new byte[colorTable.length]; byte[] ab = new byte[colorTable.length]; getColorTable(colorTable, ar, ag, ab); IndexColorModel icm = new IndexColorModel( 1, 2, ar, ag, ab ); // Create indexed image BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_BYTE_BINARY, icm ); // We'll use the raster to set samples instead of RGB values. // The SampleModel of an indexed image interprets samples as // the index of the colour for a pixel, which is perfect for use here. WritableRaster raster = img.getRaster(); //padding int dataBitsPerLine = infoHeader.iWidth; int bitsPerLine = dataBitsPerLine; if (bitsPerLine % 32 != 0) { bitsPerLine = (bitsPerLine / 32 + 1) * 32; } int padBits = bitsPerLine - dataBitsPerLine; int padBytes = padBits / 8; int bytesPerLine = (int) (bitsPerLine / 8); int[] line = new int[bytesPerLine]; for (int y = infoHeader.iHeight - 1; y >= 0; y--) { for (int i = 0; i < bytesPerLine; i++) { line[i] = lis.readUnsignedByte(); } for (int x = 0; x < infoHeader.iWidth; x++) { int i = x / 8; int v = line[i]; int b = x % 8; int index = getBit(v, b); //int rgb = c[index]; //img.setRGB(x, y, rgb); //set the sample (colour index) for the pixel raster.setSample(x, y, 0, index); } } return img; } /** * Reads 4-bit uncompressed bitmap raster data, which is interpreted based on the colours * specified in the palette. * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @param lis the source input * @param colorTable <tt>ColorEntry</tt> array specifying the palette, which * must not be <tt>null</tt>. * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read4(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis, ColorEntry[] colorTable) throws IOException { // 2 pixels per byte or 4 bits per pixel. // Colour for each pixel specified by the color index in the pallette. byte[] ar = new byte[colorTable.length]; byte[] ag = new byte[colorTable.length]; byte[] ab = new byte[colorTable.length]; getColorTable(colorTable, ar, ag, ab); IndexColorModel icm = new IndexColorModel( 4, infoHeader.iNumColors, ar, ag, ab ); BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_BYTE_BINARY, icm ); WritableRaster raster = img.getRaster(); //padding int bitsPerLine = infoHeader.iWidth * 4; if (bitsPerLine % 32 != 0) { bitsPerLine = (bitsPerLine / 32 + 1) * 32; } int bytesPerLine = (int) (bitsPerLine / 8); int[] line = new int[bytesPerLine]; for (int y = infoHeader.iHeight - 1; y >= 0; y--) { //scan line for (int i = 0; i < bytesPerLine; i++) { int b = lis.readUnsignedByte(); line[i] = b; } //get pixels for (int x = 0; x < infoHeader.iWidth; x++) { //get byte index for line int b = x / 2; // 2 pixels per byte int i = x % 2; int n = line[b]; int index = getNibble(n, i); raster.setSample(x, y, 0, index); } } return img; } /** * Reads 8-bit uncompressed bitmap raster data, which is interpreted based on the colours * specified in the palette. * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @param lis the source input * @param colorTable <tt>ColorEntry</tt> array specifying the palette, which * must not be <tt>null</tt>. * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read8(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis, ColorEntry[] colorTable) throws IOException { //1 byte per pixel // color index 1 (index of color in palette) //lines padded to nearest 32bits //no alpha byte[] ar = new byte[colorTable.length]; byte[] ag = new byte[colorTable.length]; byte[] ab = new byte[colorTable.length]; getColorTable(colorTable, ar, ag, ab); IndexColorModel icm = new IndexColorModel( 8, infoHeader.iNumColors, ar, ag, ab ); BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_BYTE_INDEXED, icm ); WritableRaster raster = img.getRaster(); /* //create color pallette int[] c = new int[infoHeader.iNumColors]; for (int i = 0; i < c.length; i++) { int r = colorTable[i].bRed; int g = colorTable[i].bGreen; int b = colorTable[i].bBlue; c[i] = (r << 16) | (g << 8) | (b); } */ //padding int dataPerLine = infoHeader.iWidth; int bytesPerLine = dataPerLine; if (bytesPerLine % 4 != 0) { bytesPerLine = (bytesPerLine / 4 + 1) * 4; } int padBytesPerLine = bytesPerLine - dataPerLine; for (int y = infoHeader.iHeight - 1; y >= 0; y--) { for (int x = 0; x < infoHeader.iWidth; x++) { int b = lis.readUnsignedByte(); //int clr = c[b]; //img.setRGB(x, y, clr); //set sample (colour index) for pixel raster.setSample(x, y , 0, b); } lis.skip(padBytesPerLine); } return img; } /** * Reads 24-bit uncompressed bitmap raster data. * @param lis the source input * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read24(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis) throws IOException { //3 bytes per pixel // blue 1 // green 1 // red 1 // lines padded to nearest 32 bits // no alpha BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_INT_RGB ); WritableRaster raster = img.getRaster(); //padding to nearest 32 bits int dataPerLine = infoHeader.iWidth * 3; int bytesPerLine = dataPerLine; if (bytesPerLine % 4 != 0) { bytesPerLine = (bytesPerLine / 4 + 1) * 4; } int padBytesPerLine = bytesPerLine - dataPerLine; for (int y = infoHeader.iHeight - 1; y >= 0; y--) { for (int x = 0; x < infoHeader.iWidth; x++) { int b = lis.readUnsignedByte(); int g = lis.readUnsignedByte(); int r = lis.readUnsignedByte(); //int c = 0x00000000 | (r << 16) | (g << 8) | (b); //System.out.println(x + ","+y+"="+Integer.toHexString(c)); //img.setRGB(x, y, c); raster.setSample(x, y, 0, r); raster.setSample(x, y, 1, g); raster.setSample(x, y, 2, b); } lis.skip(padBytesPerLine); } return img; } /** * Reads 32-bit uncompressed bitmap raster data, with transparency. * @param lis the source input * @param infoHeader the <tt>InfoHeader</tt> structure, which was read using * {@link #readInfoHeader(net.sf.image4j.io.LittleEndianInputStream) readInfoHeader()} * @throws java.io.IOException if an error occurs * @return the decoded image read from the source input */ public static BufferedImage read32(InfoHeader infoHeader, thridparty.image4j.LittleEndianInputStream lis) throws IOException { //4 bytes per pixel // blue 1 // green 1 // red 1 // alpha 1 //No padding since each pixel = 32 bits BufferedImage img = new BufferedImage( infoHeader.iWidth, infoHeader.iHeight, BufferedImage.TYPE_INT_ARGB ); WritableRaster rgb = img.getRaster(); WritableRaster alpha = img.getAlphaRaster(); for (int y = infoHeader.iHeight - 1; y >= 0; y--) { for (int x = 0; x < infoHeader.iWidth; x++) { int b = lis.readUnsignedByte(); int g = lis.readUnsignedByte(); int r = lis.readUnsignedByte(); int a = lis.readUnsignedByte(); rgb.setSample(x, y, 0, r); rgb.setSample(x, y, 1, g); rgb.setSample(x, y, 2, b); alpha.setSample(x, y, 0, a); } } return img; } /** * Reads and decodes BMP data from the source file. * @param file the source file * @throws java.io.IOException if an error occurs * @return the decoded image read from the source file */ public static BufferedImage read(java.io.File file) throws IOException { java.io.FileInputStream fin = new java.io.FileInputStream(file); try { return read(new BufferedInputStream(fin)); } finally { try { fin.close(); } catch (IOException ex) { } } } /** * Reads and decodes BMP data from the source input. * @param in the source input * @throws java.io.IOException if an error occurs * @return the decoded image read from the source file */ public static BufferedImage read(java.io.InputStream in) throws IOException { BMPDecoder d = new BMPDecoder(in); return d.getBufferedImage(); } /** * Reads and decodes BMP data from the source file, together with metadata. * @param file the source file * @throws java.io.IOException if an error occurs * @return the decoded image read from the source file * @since 0.7 */ public static BMPImage readExt(java.io.File file) throws IOException { java.io.FileInputStream fin = new java.io.FileInputStream(file); try { return readExt(new BufferedInputStream(fin)); } finally { try { fin.close(); } catch (IOException ex) { } } } /** * Reads and decodes BMP data from the source input, together with metadata. * @param in the source input * @throws java.io.IOException if an error occurs * @return the decoded image read from the source file * @since 0.7 */ public static BMPImage readExt(java.io.InputStream in) throws IOException { BMPDecoder d = new BMPDecoder(in); BMPImage ret = new BMPImage(d.getBufferedImage(), d.getInfoHeader()); return ret; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/image4j/LittleEndianInputStream.java
released/MyBox/src/main/java/thridparty/image4j/LittleEndianInputStream.java
/* * LittleEndianInputStream.java * * Created on 07 November 2006, 08:26 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.io.EOFException; import java.io.IOException; /** * Reads little-endian data from a source <tt>InputStream</tt> by reversing byte ordering. * @author Ian McDonagh */ public class LittleEndianInputStream extends java.io.DataInputStream implements CountingDataInput { /** * Creates a new instance of <tt>LittleEndianInputStream</tt>, which will read from the specified source. * @param in the source <tt>InputStream</tt> */ public LittleEndianInputStream(CountingInputStream in) { super(in); } @Override public int getCount() { return ((CountingInputStream) in).getCount(); } public int skip(int count, boolean strict) throws IOException { return IOUtils.skip(this, count, strict); } /** * Reads a little-endian <tt>short</tt> value * @throws java.io.IOException if an error occurs * @return <tt>short</tt> value with reversed byte order */ public short readShortLE() throws IOException { int b1 = read(); int b2 = read(); if (b1 < 0 || b2 < 0) { throw new EOFException(); } short ret = (short) ((b2 << 8) + (b1 << 0)); return ret; } /** * Reads a little-endian <tt>int</tt> value. * @throws java.io.IOException if an error occurs * @return <tt>int</tt> value with reversed byte order */ public int readIntLE() throws IOException { int b1 = read(); int b2 = read(); int b3 = read(); int b4 = read(); if (b1 < -1 || b2 < -1 || b3 < -1 || b4 < -1) { throw new EOFException(); } int ret = (b4 << 24) + (b3 << 16) + (b2 << 8) + (b1 << 0); return ret; } /** * Reads a little-endian <tt>float</tt> value. * @throws java.io.IOException if an error occurs * @return <tt>float</tt> value with reversed byte order */ public float readFloatLE() throws IOException { int i = readIntLE(); float ret = Float.intBitsToFloat(i); return ret; } /** * Reads a little-endian <tt>long</tt> value. * @throws java.io.IOException if an error occurs * @return <tt>long</tt> value with reversed byte order */ public long readLongLE() throws IOException { int i1 = readIntLE(); int i2 = readIntLE(); long ret = ((long)(i1) << 32) + (i2 & 0xFFFFFFFFL); return ret; } /** * Reads a little-endian <tt>double</tt> value. * @throws java.io.IOException if an error occurs * @return <tt>double</tt> value with reversed byte order */ public double readDoubleLE() throws IOException { long l = readLongLE(); double ret = Double.longBitsToDouble(l); return ret; } /** * @since 0.6 */ public long readUnsignedInt() throws IOException { long i1 = readUnsignedByte(); long i2 = readUnsignedByte(); long i3 = readUnsignedByte(); long i4 = readUnsignedByte(); long ret = ((i1 << 24) | (i2 << 16) | (i3 << 8) | i4); return ret; } /** * @since 0.6 */ public long readUnsignedIntLE() throws IOException { long i1 = readUnsignedByte(); long i2 = readUnsignedByte(); long i3 = readUnsignedByte(); long i4 = readUnsignedByte(); long ret = (i4 << 24) | (i3 << 16) | (i2 << 8) | i1; return ret; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/image4j/ConvertUtil.java
released/MyBox/src/main/java/thridparty/image4j/ConvertUtil.java
/* * ConvertUtil.java * * Created on 12 May 2006, 09:22 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package thridparty.image4j; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.DataBuffer; import java.awt.image.IndexColorModel; /** * Provides useful methods for converting images from one colour depth to another. * @author Ian McDonagh */ public class ConvertUtil { /** * Converts the source to 1-bit colour depth (monochrome). * No transparency. * @param src the source image to convert * @return a copy of the source image with a 1-bit colour depth. */ public static BufferedImage convert1(BufferedImage src) { IndexColorModel icm = new IndexColorModel( 1, 2, new byte[] { (byte) 0, (byte) 0xFF }, new byte[] { (byte) 0, (byte) 0xFF }, new byte[] { (byte) 0, (byte) 0xFF } ); BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_BINARY, icm ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } /** * Converts the source image to 4-bit colour * using the default 16-colour palette: * <ul> * <li>black</li><li>dark red</li><li>dark green</li> * <li>dark yellow</li><li>dark blue</li><li>dark magenta</li> * <li>dark cyan</li><li>dark grey</li><li>light grey</li> * <li>red</li><li>green</li><li>yellow</li><li>blue</li> * <li>magenta</li><li>cyan</li><li>white</li> * </ul> * No transparency. * @param src the source image to convert * @return a copy of the source image with a 4-bit colour depth, with the default colour pallette */ public static BufferedImage convert4(BufferedImage src) { int[] cmap = new int[] { 0x000000, 0x800000, 0x008000, 0x808000, 0x000080, 0x800080, 0x008080, 0x808080, 0xC0C0C0, 0xFF0000, 0x00FF00, 0xFFFF00, 0x0000FF, 0xFF00FF, 0x00FFFF, 0xFFFFFF }; return convert4(src, cmap); } /** * Converts the source image to 4-bit colour * using the given colour map. No transparency. * @param src the source image to convert * @param cmap the colour map, which should contain no more than 16 entries * The entries are in the form RRGGBB (hex). * @return a copy of the source image with a 4-bit colour depth, with the custom colour pallette */ public static BufferedImage convert4(BufferedImage src, int[] cmap) { IndexColorModel icm = new IndexColorModel( 4, cmap.length, cmap, 0, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE ); BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_BINARY, icm ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } /** * Converts the source image to 8-bit colour * using the default 256-colour palette. No transparency. * @param src the source image to convert * @return a copy of the source image with an 8-bit colour depth */ public static BufferedImage convert8(BufferedImage src) { BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } /** * Converts the source image to 24-bit colour (RGB). No transparency. * @param src the source image to convert * @return a copy of the source image with a 24-bit colour depth */ public static BufferedImage convert24(BufferedImage src) { BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_RGB ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } /** * Converts the source image to 32-bit colour with transparency (ARGB). * @param src the source image to convert * @return a copy of the source image with a 32-bit colour depth. */ public static BufferedImage convert32(BufferedImage src) { BufferedImage dest = new BufferedImage( src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB ); ColorConvertOp cco = new ColorConvertOp( src.getColorModel().getColorSpace(), dest.getColorModel().getColorSpace(), null ); cco.filter(src, dest); return dest; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/jankovicsandras/ImageTracer.java
released/MyBox/src/main/java/thridparty/jankovicsandras/ImageTracer.java
// https://github.com/jankovicsandras/imagetracerjava /* ImageTracer.java (Desktop version with javax.imageio. See ImageTracerAndroid.java for the Android version.) Simple raster image tracer and vectorizer written in Java. This is a port of imagetracer.js. by András Jankovics 2015, 2016 andras@jankovics.net */ /* The Unlicense / PUBLIC DOMAIN This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to http://unlicense.org/ */ package thridparty.jankovicsandras; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import java.util.TreeMap; import javax.imageio.ImageIO; import mara.mybox.dev.MyBoxLog; public class ImageTracer { public static String versionnumber = "1.1.2"; public ImageTracer() { } public static void main(String[] args) { try { if (args.length < 1) { System.out.println("ERROR: there's no input filename. Basic usage: \r\n\r\njava -jar ImageTracer.jar <filename>" + "\r\n\r\nor\r\n\r\njava -jar ImageTracer.jar help"); } else if (arraycontains(args, "help") > -1) { System.out.println("Example usage:\r\n\r\njava -jar ImageTracer.jar <filename> outfilename test.svg " + "ltres 1 qtres 1 pathomit 8 colorsampling 1 numberofcolors 16 mincolorratio 0.02 colorquantcycles 3 " + "scale 1 simplifytolerance 0 roundcoords 1 lcpr 0 qcpr 0 desc 1 viewbox 0 blurradius 0 blurdelta 20 \r\n" + "\r\nOnly <filename> is mandatory, if some of the other optional parameters are missing, they will be set to these defaults. " + "\r\nWarning: if outfilename is not specified, then <filename>.svg will be overwritten." + "\r\nSee https://github.com/jankovicsandras/imagetracerjava for details. \r\nThis is version " + versionnumber); } else { // Parameter parsing String outfilename = args[0] + ".svg"; HashMap<String, Float> options = new HashMap<String, Float>(); String[] parameternames = {"ltres", "qtres", "pathomit", "colorsampling", "numberofcolors", "mincolorratio", "colorquantcycles", "scale", "simplifytolerance", "roundcoords", "lcpr", "qcpr", "desc", "viewbox", "blurradius", "blurdelta", "outfilename"}; int j = -1; float f = -1; for (String parametername : parameternames) { j = arraycontains(args, parametername); if (j > -1) { if (parametername == "outfilename") { if (j < (args.length - 1)) { outfilename = args[j + 1]; } } else { f = parsenext(args, j); if (f > -1) { options.put(parametername, new Float(f)); } } } }// End of parameternames loop // Loading image, tracing, rendering SVG, saving SVG file saveString(outfilename, imageToSVG(args[0], options, null)); }// End of parameter parsing and processing } catch (Exception e) { e.printStackTrace(); } }// End of main() public static int arraycontains(String[] arr, String str) { for (int j = 0; j < arr.length; j++) { if (arr[j].toLowerCase().equals(str)) { return j; } } return -1; } public static float parsenext(String[] arr, int i) { if (i < (arr.length - 1)) { try { return Float.parseFloat(arr[i + 1]); } catch (Exception e) { } } return -1; } // Container for the color-indexed image before and tracedata after vectorizing public static class IndexedImage { public int width, height; public int[][] array; // array[x][y] of palette colors public byte[][] palette;// array[palettelength][4] RGBA color palette public ArrayList<ArrayList<ArrayList<Double[]>>> layers;// tracedata public IndexedImage(int[][] marray, byte[][] mpalette) { array = marray; palette = mpalette; width = marray[0].length - 2; height = marray.length - 2;// Color quantization adds +2 to the original width and height } } // https://developer.mozilla.org/en-US/docs/Web/API/ImageData public static class ImageData { public int width, height; public byte[] data; // raw byte data: R G B A R G B A ... public ImageData(int mwidth, int mheight, byte[] mdata) { width = mwidth; height = mheight; data = mdata; } } // Saving a String as a file public static void saveString(String filename, String str) throws Exception { File file = new File(filename); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(str); bw.close(); } // Loading a file to ImageData, ARGB byte order public static ImageData loadImageData(String filename) throws Exception { BufferedImage image = ImageIO.read(new File(filename)); return loadImageData(image); } public static ImageData loadImageData(BufferedImage image) throws Exception { int width = image.getWidth(); int height = image.getHeight(); int[] rawdata = image.getRGB(0, 0, width, height, null, 0, width); byte[] data = new byte[rawdata.length * 4]; for (int i = 0; i < rawdata.length; i++) { data[(i * 4) + 3] = bytetrans((byte) (rawdata[i] >>> 24)); data[i * 4] = bytetrans((byte) (rawdata[i] >>> 16)); data[(i * 4) + 1] = bytetrans((byte) (rawdata[i] >>> 8)); data[(i * 4) + 2] = bytetrans((byte) (rawdata[i])); } return new ImageData(width, height, data); } // The bitshift method in loadImageData creates signed bytes where -1 -> 255 unsigned ; -128 -> 128 unsigned ; // 127 -> 127 unsigned ; 0 -> 0 unsigned ; These will be converted to -128 (representing 0 unsigned) ... // 127 (representing 255 unsigned) and tosvgcolorstr will add +128 to create RGB values 0..255 public static byte bytetrans(byte b) { if (b < 0) { return (byte) (b + 128); } else { return (byte) (b - 128); } } //////////////////////////////////////////////////////////// // // User friendly functions // //////////////////////////////////////////////////////////// // Loading an image from a file, tracing when loaded, then returning the SVG String public static String imageToSVG(String filename, HashMap<String, Float> options, byte[][] palette) throws Exception { options = checkoptions(options); ImageData imgd = loadImageData(filename); return imagedataToSVG(imgd, options, palette); }// End of imageToSVG() public static String imageToSVG(BufferedImage image, HashMap<String, Float> options, byte[][] palette) throws Exception { options = checkoptions(options); ImageData imgd = loadImageData(image); return imagedataToSVG(imgd, options, palette); }// End of imageToSVG() // Tracing ImageData, then returning the SVG String public static String imagedataToSVG(ImageData imgd, HashMap<String, Float> options, byte[][] palette) { options = checkoptions(options); IndexedImage ii = imagedataToTracedata(imgd, options, palette); return getsvgstring(ii, options); }// End of imagedataToSVG() // Loading an image from a file, tracing when loaded, then returning IndexedImage with tracedata in layers public IndexedImage imageToTracedata(String filename, HashMap<String, Float> options, byte[][] palette) throws Exception { options = checkoptions(options); ImageData imgd = loadImageData(filename); return imagedataToTracedata(imgd, options, palette); }// End of imageToTracedata() public IndexedImage imageToTracedata(BufferedImage image, HashMap<String, Float> options, byte[][] palette) throws Exception { options = checkoptions(options); ImageData imgd = loadImageData(image); return imagedataToTracedata(imgd, options, palette); }// End of imageToTracedata() // Tracing ImageData, then returning IndexedImage with tracedata in layers public static IndexedImage imagedataToTracedata(ImageData imgd, HashMap<String, Float> options, byte[][] palette) { // 1. Color quantization IndexedImage ii = colorquantization(imgd, palette, options); // 2. Layer separation and edge detection int[][][] rawlayers = layering(ii); // 3. Batch pathscan ArrayList<ArrayList<ArrayList<Integer[]>>> bps = batchpathscan(rawlayers, (int) (Math.floor(options.get("pathomit")))); // 4. Batch interpollation ArrayList<ArrayList<ArrayList<Double[]>>> bis = batchinternodes(bps); // 5. Batch tracing ii.layers = batchtracelayers(bis, options.get("ltres"), options.get("qtres")); return ii; }// End of imagedataToTracedata() // creating options object, setting defaults for missing values public static HashMap<String, Float> checkoptions(HashMap<String, Float> options) { if (options == null) { options = new HashMap<String, Float>(); } // Tracing if (!options.containsKey("ltres")) { options.put("ltres", 1f); } if (!options.containsKey("qtres")) { options.put("qtres", 1f); } if (!options.containsKey("pathomit")) { options.put("pathomit", 8f); } // Color quantization if (!options.containsKey("colorsampling")) { options.put("colorsampling", 1f); } if (!options.containsKey("numberofcolors")) { options.put("numberofcolors", 16f); } if (!options.containsKey("mincolorratio")) { options.put("mincolorratio", 0.02f); } if (!options.containsKey("colorquantcycles")) { options.put("colorquantcycles", 3f); } // SVG rendering if (!options.containsKey("scale")) { options.put("scale", 1f); } if (!options.containsKey("simplifytolerance")) { options.put("simplifytolerance", 0f); } if (!options.containsKey("roundcoords")) { options.put("roundcoords", 1f); } if (!options.containsKey("lcpr")) { options.put("lcpr", 0f); } if (!options.containsKey("qcpr")) { options.put("qcpr", 0f); } if (!options.containsKey("desc")) { options.put("desc", 1f); } if (!options.containsKey("viewbox")) { options.put("viewbox", 0f); } // Blur if (!options.containsKey("blurradius")) { options.put("blurradius", 0f); } if (!options.containsKey("blurdelta")) { options.put("blurdelta", 20f); } return options; }// End of checkoptions() //////////////////////////////////////////////////////////// // // Vectorizing functions // //////////////////////////////////////////////////////////// // 1. Color quantization repeated "cycles" times, based on K-means clustering // https://en.wikipedia.org/wiki/Color_quantization https://en.wikipedia.org/wiki/K-means_clustering public static IndexedImage colorquantization(ImageData imgd, byte[][] palette, HashMap<String, Float> options) { int numberofcolors = (int) Math.floor(options.get("numberofcolors")); float minratio = options.get("mincolorratio"); int cycles = (int) Math.floor(options.get("colorquantcycles")); // Creating indexed color array arr which has a boundary filled with -1 in every direction int[][] arr = new int[imgd.height + 2][imgd.width + 2]; for (int j = 0; j < (imgd.height + 2); j++) { arr[j][0] = -1; arr[j][imgd.width + 1] = -1; } for (int i = 0; i < (imgd.width + 2); i++) { arr[0][i] = -1; arr[imgd.height + 1][i] = -1; } int idx = 0, cd, cdl, ci, c1, c2, c3, c4; // Use custom palette if pal is defined or sample or generate custom length palette if (palette == null) { if (options.get("colorsampling") != 0) { palette = samplepalette(numberofcolors, imgd); } else { palette = generatepalette(numberofcolors); } } // Selective Gaussian blur preprocessing if (options.get("blurradius") > 0) { imgd = blur(imgd, options.get("blurradius"), options.get("blurdelta")); } long[][] paletteacc = new long[palette.length][5]; // Repeat clustering step "cycles" times for (int cnt = 0; cnt < cycles; cnt++) { // Average colors from the second iteration if (cnt > 0) { // averaging paletteacc for palette float ratio; for (int k = 0; k < palette.length; k++) { // averaging if (paletteacc[k][3] > 0) { palette[k][0] = (byte) (-128 + (paletteacc[k][0] / paletteacc[k][4])); palette[k][1] = (byte) (-128 + (paletteacc[k][1] / paletteacc[k][4])); palette[k][2] = (byte) (-128 + (paletteacc[k][2] / paletteacc[k][4])); palette[k][3] = (byte) (-128 + (paletteacc[k][3] / paletteacc[k][4])); } ratio = (float) ((double) (paletteacc[k][4]) / (double) (imgd.width * imgd.height)); // Randomizing a color, if there are too few pixels and there will be a new cycle if ((ratio < minratio) && (cnt < (cycles - 1))) { palette[k][0] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[k][1] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[k][2] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[k][3] = (byte) (-128 + Math.floor(Math.random() * 255)); } }// End of palette loop }// End of Average colors from the second iteration // Reseting palette accumulator for averaging for (int i = 0; i < palette.length; i++) { paletteacc[i][0] = 0; paletteacc[i][1] = 0; paletteacc[i][2] = 0; paletteacc[i][3] = 0; paletteacc[i][4] = 0; } // loop through all pixels for (int j = 0; j < imgd.height; j++) { for (int i = 0; i < imgd.width; i++) { idx = ((j * imgd.width) + i) * 4; // find closest color from palette by measuring (rectilinear) color distance between this pixel and all palette colors cdl = 256 + 256 + 256 + 256; ci = 0; for (int k = 0; k < palette.length; k++) { // In my experience, https://en.wikipedia.org/wiki/Rectilinear_distance works better than https://en.wikipedia.org/wiki/Euclidean_distance c1 = Math.abs(palette[k][0] - imgd.data[idx]); c2 = Math.abs(palette[k][1] - imgd.data[idx + 1]); c3 = Math.abs(palette[k][2] - imgd.data[idx + 2]); c4 = Math.abs(palette[k][3] - imgd.data[idx + 3]); cd = c1 + c2 + c3 + (c4 * 4); // weighted alpha seems to help images with transparency // Remember this color if this is the closest yet if (cd < cdl) { cdl = cd; ci = k; } }// End of palette loop // add to palettacc paletteacc[ci][0] += 128 + imgd.data[idx]; paletteacc[ci][1] += 128 + imgd.data[idx + 1]; paletteacc[ci][2] += 128 + imgd.data[idx + 2]; paletteacc[ci][3] += 128 + imgd.data[idx + 3]; paletteacc[ci][4]++; arr[j + 1][i + 1] = ci; }// End of i loop }// End of j loop }// End of Repeat clustering step "cycles" times return new IndexedImage(arr, palette); }// End of colorquantization // Generating a palette with numberofcolors, array[numberofcolors][4] where [i][0] = R ; [i][1] = G ; [i][2] = B ; [i][3] = A public static byte[][] generatepalette(int numberofcolors) { byte[][] palette = new byte[numberofcolors][4]; if (numberofcolors < 8) { // Grayscale double graystep = 255.0 / (double) (numberofcolors - 1); for (byte ccnt = 0; ccnt < numberofcolors; ccnt++) { palette[ccnt][0] = (byte) (-128 + Math.round(ccnt * graystep)); palette[ccnt][1] = (byte) (-128 + Math.round(ccnt * graystep)); palette[ccnt][2] = (byte) (-128 + Math.round(ccnt * graystep)); palette[ccnt][3] = (byte) 127; } } else { // RGB color cube int colorqnum = (int) Math.floor(Math.pow(numberofcolors, 1.0 / 3.0)); // Number of points on each edge on the RGB color cube int colorstep = (int) Math.floor(255 / (colorqnum - 1)); // distance between points int ccnt = 0; for (int rcnt = 0; rcnt < colorqnum; rcnt++) { for (int gcnt = 0; gcnt < colorqnum; gcnt++) { for (int bcnt = 0; bcnt < colorqnum; bcnt++) { palette[ccnt][0] = (byte) (-128 + (rcnt * colorstep)); palette[ccnt][1] = (byte) (-128 + (gcnt * colorstep)); palette[ccnt][2] = (byte) (-128 + (bcnt * colorstep)); palette[ccnt][3] = (byte) 127; ccnt++; }// End of blue loop }// End of green loop }// End of red loop // Rest is random for (int rcnt = ccnt; rcnt < numberofcolors; rcnt++) { palette[ccnt][0] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[ccnt][1] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[ccnt][2] = (byte) (-128 + Math.floor(Math.random() * 255)); palette[ccnt][3] = (byte) (-128 + Math.floor(Math.random() * 255)); } }// End of numberofcolors check return palette; } ;// End of generatepalette() public static byte[][] samplepalette(int numberofcolors, ImageData imgd) { int idx = 0; byte[][] palette = new byte[numberofcolors][4]; for (int i = 0; i < numberofcolors; i++) { idx = (int) (Math.floor((Math.random() * imgd.data.length) / 4) * 4); palette[i][0] = imgd.data[idx]; palette[i][1] = imgd.data[idx + 1]; palette[i][2] = imgd.data[idx + 2]; palette[i][3] = imgd.data[idx + 3]; } return palette; }// End of samplepalette() // 2. Layer separation and edge detection // Edge node types ( ▓:light or 1; ░:dark or 0 ) // 12 ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ // 48 ░░ ░░ ░░ ░░ ░▓ ░▓ ░▓ ░▓ ▓░ ▓░ ▓░ ▓░ ▓▓ ▓▓ ▓▓ ▓▓ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // public static int[][][] layering(IndexedImage ii) { try { // Creating layers for each indexed color in arr int val = 0, aw = ii.array[0].length, ah = ii.array.length, n1, n2, n3, n4, n5, n6, n7, n8; int[][][] layers = new int[ii.palette.length][ah][aw]; // Looping through all pixels and calculating edge node type for (int j = 1; j < (ah - 1); j++) { for (int i = 1; i < (aw - 1); i++) { // This pixel's indexed color val = ii.array[j][i]; // Are neighbor pixel colors the same? n1 = ii.array[j - 1][i - 1] == val ? 1 : 0; n2 = ii.array[j - 1][i] == val ? 1 : 0; n3 = ii.array[j - 1][i + 1] == val ? 1 : 0; n4 = ii.array[j][i - 1] == val ? 1 : 0; n5 = ii.array[j][i + 1] == val ? 1 : 0; n6 = ii.array[j + 1][i - 1] == val ? 1 : 0; n7 = ii.array[j + 1][i] == val ? 1 : 0; n8 = ii.array[j + 1][i + 1] == val ? 1 : 0; // this pixel"s type and looking back on previous pixels layers[val][j + 1][i + 1] = 1 + (n5 * 2) + (n8 * 4) + (n7 * 8); if (n4 == 0) { layers[val][j + 1][i] = 0 + 2 + (n7 * 4) + (n6 * 8); } if (n2 == 0) { layers[val][j][i + 1] = 0 + (n3 * 2) + (n5 * 4) + 8; } if (n1 == 0) { layers[val][j][i] = 0 + (n2 * 2) + 4 + (n4 * 8); } }// End of i loop }// End of j loop return layers; } catch (Exception e) { MyBoxLog.error(e); return null; } }// End of layering() // Lookup tables for pathscan static byte[] pathscan_dir_lookup = {0, 0, 3, 0, 1, 0, 3, 0, 0, 3, 3, 1, 0, 3, 0, 0}; static boolean[] pathscan_holepath_lookup = {false, false, false, false, false, false, false, true, false, false, false, true, false, true, true, false}; // pathscan_combined_lookup[ arr[py][px] ][ dir ] = [nextarrpypx, nextdir, deltapx, deltapy]; static byte[][][] pathscan_combined_lookup = { {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}},// arr[py][px]==0 is invalid {{0, 1, 0, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 2, -1, 0}}, {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 1, 0, -1}, {0, 0, 1, 0}}, {{0, 0, 1, 0}, {-1, -1, -1, -1}, {0, 2, -1, 0}, {-1, -1, -1, -1}}, {{-1, -1, -1, -1}, {0, 0, 1, 0}, {0, 3, 0, 1}, {-1, -1, -1, -1}}, {{13, 3, 0, 1}, {13, 2, -1, 0}, {7, 1, 0, -1}, {7, 0, 1, 0}}, {{-1, -1, -1, -1}, {0, 1, 0, -1}, {-1, -1, -1, -1}, {0, 3, 0, 1}}, {{0, 3, 0, 1}, {0, 2, -1, 0}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}, {{0, 3, 0, 1}, {0, 2, -1, 0}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}, {{-1, -1, -1, -1}, {0, 1, 0, -1}, {-1, -1, -1, -1}, {0, 3, 0, 1}}, {{11, 1, 0, -1}, {14, 0, 1, 0}, {14, 3, 0, 1}, {11, 2, -1, 0}}, {{-1, -1, -1, -1}, {0, 0, 1, 0}, {0, 3, 0, 1}, {-1, -1, -1, -1}}, {{0, 0, 1, 0}, {-1, -1, -1, -1}, {0, 2, -1, 0}, {-1, -1, -1, -1}}, {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 1, 0, -1}, {0, 0, 1, 0}}, {{0, 1, 0, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {0, 2, -1, 0}}, {{-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}, {-1, -1, -1, -1}}// arr[py][px]==15 is invalid }; // 3. Walking through an edge node array, discarding edge node types 0 and 15 and creating paths from the rest. // Walk directions (dir): 0 > ; 1 ^ ; 2 < ; 3 v // Edge node types ( ▓:light or 1; ░:dark or 0 ) // ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ ░░ ▓░ ░▓ ▓▓ // ░░ ░░ ░░ ░░ ░▓ ░▓ ░▓ ░▓ ▓░ ▓░ ▓░ ▓░ ▓▓ ▓▓ ▓▓ ▓▓ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // public static ArrayList<ArrayList<Integer[]>> pathscan(int[][] arr, float pathomit) { try { ArrayList<ArrayList<Integer[]>> paths = new ArrayList<ArrayList<Integer[]>>(); ArrayList<Integer[]> thispath; int px = 0, py = 0, w = arr[0].length, h = arr.length, dir = 0; boolean pathfinished = true, holepath = false; byte[] lookuprow; for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { if ((arr[j][i] != 0) && (arr[j][i] != 15)) { // Init px = i; py = j; paths.add(new ArrayList<Integer[]>()); thispath = paths.get(paths.size() - 1); pathfinished = false; // fill paths will be drawn, but hole paths are also required to remove unnecessary edge nodes dir = pathscan_dir_lookup[arr[py][px]]; holepath = pathscan_holepath_lookup[arr[py][px]]; // Path points loop while (!pathfinished) { // New path point thispath.add(new Integer[3]); thispath.get(thispath.size() - 1)[0] = px - 1; thispath.get(thispath.size() - 1)[1] = py - 1; thispath.get(thispath.size() - 1)[2] = arr[py][px]; // Next: look up the replacement, direction and coordinate changes = clear this cell, turn if required, walk forward lookuprow = pathscan_combined_lookup[arr[py][px]][dir]; arr[py][px] = lookuprow[0]; dir = lookuprow[1]; px += lookuprow[2]; py += lookuprow[3]; // Close path if (((px - 1) == thispath.get(0)[0]) && ((py - 1) == thispath.get(0)[1])) { pathfinished = true; // Discarding 'hole' type paths and paths shorter than pathomit if ((holepath) || (thispath.size() < pathomit)) { paths.remove(thispath); } } }// End of Path points loop }// End of Follow path }// End of i loop }// End of j loop return paths; } catch (Exception e) { MyBoxLog.error(e); return null; } }// End of pathscan() // 3. Batch pathscan public static ArrayList<ArrayList<ArrayList<Integer[]>>> batchpathscan(int[][][] layers, float pathomit) { ArrayList<ArrayList<ArrayList<Integer[]>>> bpaths = new ArrayList<ArrayList<ArrayList<Integer[]>>>(); for (int[][] layer : layers) { bpaths.add(pathscan(layer, pathomit)); } return bpaths; } // 4. interpolating between path points for nodes with 8 directions ( East, SouthEast, S, SW, W, NW, N, NE ) public static ArrayList<ArrayList<Double[]>> internodes(ArrayList<ArrayList<Integer[]>> paths) { ArrayList<ArrayList<Double[]>> ins = new ArrayList<ArrayList<Double[]>>(); ArrayList<Double[]> thisinp; Double[] thispoint, nextpoint = new Double[2]; Integer[] pp1, pp2, pp3; int palen = 0, nextidx = 0, nextidx2 = 0; // paths loop for (int pacnt = 0; pacnt < paths.size(); pacnt++) { ins.add(new ArrayList<Double[]>()); thisinp = ins.get(ins.size() - 1); palen = paths.get(pacnt).size(); // pathpoints loop for (int pcnt = 0; pcnt < palen; pcnt++) { // interpolate between two path points nextidx = (pcnt + 1) % palen; nextidx2 = (pcnt + 2) % palen; thisinp.add(new Double[3]); thispoint = thisinp.get(thisinp.size() - 1); pp1 = paths.get(pacnt).get(pcnt); pp2 = paths.get(pacnt).get(nextidx); pp3 = paths.get(pacnt).get(nextidx2); thispoint[0] = (pp1[0] + pp2[0]) / 2.0; thispoint[1] = (pp1[1] + pp2[1]) / 2.0; nextpoint[0] = (pp2[0] + pp3[0]) / 2.0; nextpoint[1] = (pp2[1] + pp3[1]) / 2.0; // line segment direction to the next point if (thispoint[0] < nextpoint[0]) { if (thispoint[1] < nextpoint[1]) { thispoint[2] = 1.0; }// SouthEast else if (thispoint[1] > nextpoint[1]) { thispoint[2] = 7.0; }// NE else { thispoint[2] = 0.0; } // E } else if (thispoint[0] > nextpoint[0]) { if (thispoint[1] < nextpoint[1]) { thispoint[2] = 3.0; }// SW else if (thispoint[1] > nextpoint[1]) { thispoint[2] = 5.0; }// NW else { thispoint[2] = 4.0; }// W } else { if (thispoint[1] < nextpoint[1]) { thispoint[2] = 2.0; }// S else if (thispoint[1] > nextpoint[1]) { thispoint[2] = 6.0; }// N else { thispoint[2] = 8.0; }// center, this should not happen } }// End of pathpoints loop }// End of paths loop return ins; }// End of internodes() // 4. Batch interpollation public static ArrayList<ArrayList<ArrayList<Double[]>>> batchinternodes(ArrayList<ArrayList<ArrayList<Integer[]>>> bpaths) { ArrayList<ArrayList<ArrayList<Double[]>>> binternodes = new ArrayList<ArrayList<ArrayList<Double[]>>>(); for (int k = 0; k < bpaths.size(); k++) { binternodes.add(internodes(bpaths.get(k))); } return binternodes; } // 5. tracepath() : recursively trying to fit straight and quadratic spline segments on the 8 direction internode path // 5.1. Find sequences of points with only 2 segment types // 5.2. Fit a straight line on the sequence // 5.3. If the straight line fails (an error>ltreshold), find the point with the biggest error // 5.4. Fit a quadratic spline through errorpoint (project this to get controlpoint), then measure errors on every point in the sequence
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/IgnoreResourceHandler.java
released/MyBox/src/main/java/thridparty/pdfdom/IgnoreResourceHandler.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.IOException; public class IgnoreResourceHandler implements HtmlResourceHandler { public String handleResource(HtmlResource resource) throws IOException { return ""; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/HtmlDivLine.java
released/MyBox/src/main/java/thridparty/pdfdom/HtmlDivLine.java
/** * HtmlDivLine.java * * Created on 13. 10. 2022, 11:33:54 by burgetr */ package thridparty.pdfdom; /** * Maps input line to an HTML div rectangle, since HTML does not support standard lines. */ public class HtmlDivLine { private final float x1; private final float y1; private final float x2; private final float y2; private final float width; private final float height; private final float lineWidth; //horizontal or vertical lines are treated separately (no rotations used) private final boolean horizontal; private final boolean vertical; public HtmlDivLine(float x1, float y1, float x2, float y2, float lineWidth) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.lineWidth = lineWidth; this.width = Math.abs(x2 - x1); this.height = Math.abs(y2 - y1); this.horizontal = (height < 0.5f); this.vertical = (width < 0.5f); } public float getHeight() { return vertical ? height : 0; } public float getWidth() { if (vertical) return 0; else if (horizontal) return width; else return distanceFormula(x1, y1, x2, y2); } public float getLeft() { if (horizontal || vertical) return Math.min(x1, x2); else return Math.abs((x2 + x1) / 2) - getWidth() / 2; } public float getTop() { if (horizontal || vertical) return Math.min(y1, y2); else // after rotation top left will be center of line so find the midpoint and correct for the line to border transform return Math.abs((y2 + y1) / 2) - (getLineStrokeWidth() + getHeight()) / 2; } public double getAngleDegrees() { if (horizontal || vertical) return 0; else return Math.toDegrees(Math.atan((y2 - y1) / (x2 - x1))); } public float getLineStrokeWidth() { float lw = lineWidth; if (lw < 0.5f) lw = 0.5f; return lw; } public boolean isVertical() { return vertical; } public String getBorderSide() { return vertical ? "border-right" : "border-bottom"; } private float distanceFormula(float x1, float y1, float x2, float y2) { return (float) Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/FontTable.java
released/MyBox/src/main/java/thridparty/pdfdom/FontTable.java
/** * */ package thridparty.pdfdom; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import mara.mybox.dev.MyBoxLog; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDFontDescriptor; import org.apache.pdfbox.pdmodel.font.PDType0Font; import org.apache.pdfbox.pdmodel.font.PDType1CFont; import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.mabb.fontverter.FVFont; import org.mabb.fontverter.FontVerter; import org.mabb.fontverter.pdf.PdfFontExtractor; /** * A table for storing entries about the embedded fonts and their usage. * * @author burgetr * * Updated by Mara */ public class FontTable { private static final Pattern fontFamilyRegex = Pattern.compile("([^+^-]*)[+-]([^+]*)"); private final List<Entry> entries = new ArrayList<>(); public void addEntry(PDFont font) { try { FontTable.Entry entry = get(font); if (entry == null) { String fontName = font.getName(); String family = findFontFamily(fontName); String usedName = nextUsedName(family); FontTable.Entry newEntry = new FontTable.Entry(font.getName(), usedName, font); if (newEntry.isEntryValid()) { add(newEntry); } } } catch (Exception e) { MyBoxLog.console(e.toString()); } } public Entry get(PDFont find) { try { for (Entry entryOn : entries) { if (entryOn.equalToPDFont(find)) { return entryOn; } } } catch (Exception e) { MyBoxLog.console(e.toString()); } return null; } public List<Entry> getEntries() { return new ArrayList<>(entries); } public String getUsedName(PDFont font) { FontTable.Entry entry = get(font); if (entry == null) { return null; } else { return entry.usedName; } } protected String nextUsedName(String fontName) { int i = 1; String usedName = fontName; while (isNameUsed(usedName)) { usedName = fontName + i; i++; } return usedName; } protected boolean isNameUsed(String name) { for (Entry entryOn : entries) { if (entryOn.usedName.equals(name)) { return true; } } return false; } protected void add(Entry entry) { entries.add(entry); } private String findFontFamily(String fontName) { // pdf font family name isn't always populated so have to find ourselves from full name String familyName = fontName; Matcher familyMatcher = fontFamilyRegex.matcher(fontName); if (familyMatcher.find()) // currently tacking on weight/style too since we don't generate html for it yet // and it's helpful for debugugging { familyName = familyMatcher.group(1) + " " + familyMatcher.group(2); } // browsers will barf if + in family name return familyName.replaceAll("[+]", " "); } public class Entry extends HtmlResource { public String fontName; public String usedName; public PDFontDescriptor descriptor; private final PDFont baseFont; private byte[] cachedFontData; private String mimeType = "x-font-truetype"; private String fileEnding; public Entry(String fontName, String usedName, PDFont font) { super(fontName); this.fontName = fontName; this.usedName = usedName; this.descriptor = font.getFontDescriptor(); this.baseFont = font; } @Override public byte[] getData() { try { if (cachedFontData != null) { return cachedFontData; } if (baseFont instanceof PDType1CFont || baseFont instanceof PDType1Font) { cachedFontData = loadType1Font(descriptor.getFontFile3()); } else if (descriptor.getFontFile2() != null && baseFont instanceof PDType0Font) { cachedFontData = loadType0TtfDescendantFont(); } else if (descriptor.getFontFile2() != null) { cachedFontData = loadTrueTypeFont(descriptor.getFontFile2()); } else if (descriptor.getFontFile() != null) { cachedFontData = loadType1Font(descriptor.getFontFile()); } else if (descriptor.getFontFile3() != null) { // FontFile3 docs say any font type besides TTF/OTF or Type 1.. cachedFontData = loadOtherTypeFont(descriptor.getFontFile3()); } return cachedFontData; } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } public boolean isEntryValid() { try { byte[] fontData = new byte[0]; fontData = getData(); return fontData != null && fontData.length != 0; } catch (Exception e) { MyBoxLog.console(e.toString()); return false; } } private byte[] loadTrueTypeFont(PDStream fontFile) { // MyBoxLog.console("Fail to convert True Type fonts."); // try { // // could convert to WOFF though for optimal html output instead. // FVFont font = FontVerter.readFont(fontFile.toByteArray()); // if (font != null) { // byte[] fvFontData = tryNormalizeFVFont(font); // if (fvFontData != null && fvFontData.length != 0) { // mimeType = "application/x-font-truetype"; // fileEnding = "otf"; // return fvFontData; // } // } // } catch (Exception e) { // MyBoxLog.console("Unsupported FontFile found. Normalisation will be skipped."); // MyBoxLog.console(e.toString()); // } return new byte[0]; } private byte[] loadType0TtfDescendantFont() { mimeType = "application/x-font-truetype"; fileEnding = "ttf"; try { FVFont font = PdfFontExtractor.convertType0FontToOpenType((PDType0Font) baseFont); byte[] fontData = tryNormalizeFVFont(font); if (fontData.length != 0) { return fontData; } } catch (Exception ex) { // MyBoxLog.console("Error loading type 0 with ttf descendant font '{}' Message: {} {}", // fontName + " " + ex.getMessage() + " " + ex.getClass()); } try { return descriptor.getFontFile2().toByteArray(); } catch (Exception ex) { return new byte[0]; } } private byte[] loadType1Font(PDStream fontFile) { // MyBoxLog.console("Type 1 fonts are not supported by Pdf2Dom."); return new byte[0]; } private byte[] loadOtherTypeFont(PDStream fontFile) { // Likley Bare CFF which needs to be converted to a font supported by browsers, can be // other font types which are not yet supported. try { FVFont font = FontVerter.convertFont(fontFile.toByteArray(), FontVerter.FontFormat.WOFF1); mimeType = "application/x-font-woff"; fileEnding = font.getProperties().getFileEnding(); return font.getData(); } catch (Exception ex) { // MyBoxLog.console("Issue converting Bare CFF font or the font type is not supportedby Pdf2Dom, " // + "Font: {} Exception: {} {}" + " " + fontName, ex.getMessage() + " " + ex.getClass()); // don't barf completley for font conversion issue, html will still be useable without. return new byte[0]; } } private byte[] tryNormalizeFVFont(FVFont font) { try { // browser validation can fail for many TTF fonts from pdfs if (!font.isValid()) { font.normalize(); } return font.getData(); } catch (Exception ex) { // MyBoxLog.console("Error normalizing font '{}' Message: {} {}", // fontName + " " + ex.getMessage() + " " + ex.getClass()); } return new byte[0]; } public boolean equalToPDFont(PDFont compare) { // Appears you can have two different fonts with the same actual font name since text position font // references go off a seperate dict lookup name. PDFBox doesn't include the lookup name with the // PDFont, so might have to submit a change there to be really sure fonts are indeed the same. return compare.getName().equals(baseFont.getName()) && compare.getType().equals(baseFont.getType()) && compare.getSubType().equals(baseFont.getSubType()); } @Override public int hashCode() { return fontName.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Entry other = (Entry) obj; if (!getOuterType().equals(other.getOuterType())) { return false; } if (fontName == null) { if (other.fontName != null) { return false; } } else if (!fontName.equals(other.fontName)) { return false; } return true; } @Override public String getFileEnding() { return fileEnding; } private FontTable getOuterType() { return FontTable.this; } @Override public String getMimeType() { return mimeType; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/PDFDomTreeConfig.java
released/MyBox/src/main/java/thridparty/pdfdom/PDFDomTreeConfig.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.File; public class PDFDomTreeConfig { private HtmlResourceHandler imageHandler; private HtmlResourceHandler fontHandler; public static PDFDomTreeConfig createDefaultConfig() { PDFDomTreeConfig config = new PDFDomTreeConfig(); config.setFontHandler(embedAsBase64()); config.setImageHandler(embedAsBase64()); return config; } public static HtmlResourceHandler embedAsBase64() { return new EmbedAsBase64Handler(); } public static HtmlResourceHandler saveToDirectory(File directory) { return new SaveResourceToDirHandler(directory); } public static HtmlResourceHandler ignoreResource() { return new IgnoreResourceHandler(); } private PDFDomTreeConfig() { } public HtmlResourceHandler getImageHandler() { return imageHandler; } public void setImageHandler(HtmlResourceHandler imageHandler) { this.imageHandler = imageHandler; } public HtmlResourceHandler getFontHandler() { return fontHandler; } public void setFontHandler(HtmlResourceHandler fontHandler) { this.fontHandler = fontHandler; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/SaveResourceToDirHandler.java
released/MyBox/src/main/java/thridparty/pdfdom/SaveResourceToDirHandler.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import org.apache.commons.io.FileUtils; public class SaveResourceToDirHandler implements HtmlResourceHandler { public static final String DEFAULT_RESOURCE_DIR = "resources/"; private final File directory; private List<String> writtenFileNames = new LinkedList<>(); public SaveResourceToDirHandler() { directory = null; } public SaveResourceToDirHandler(File directory) { this.directory = directory; } @Override public String handleResource(HtmlResource resource) throws IOException { String dir = DEFAULT_RESOURCE_DIR; if (directory != null) { dir = directory.getPath() + "/"; } String fileName = findNextUnusedFileName(resource.getName()); String resourcePath = dir + fileName + "." + resource.getFileEnding(); File file = new File(resourcePath); FileUtils.writeByteArrayToFile(file, resource.getData()); writtenFileNames.add(fileName); // #### write relative path in html. Changed by Mara return new File(dir).getName() + File.separator + fileName + "." + resource.getFileEnding(); // return "file:///" + resourcePath; // For FireFox and WebView // return resourcePath; } private String findNextUnusedFileName(String fileName) { int i = 1; String usedName = fileName; while (writtenFileNames.contains(usedName)) { usedName = fileName + i; i++; } return usedName; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/BoxStyle.java
released/MyBox/src/main/java/thridparty/pdfdom/BoxStyle.java
/** * BoxStyle.java * (c) Radek Burget, 2011 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 16.9.2011, 22:29:26 by radek */ package thridparty.pdfdom; /** * This class represents a style of a text box. * @author radek */ public class BoxStyle { public static final String defaultColor = "#000000"; public static final String defaultFontWeight = "normal"; public static final String defaultFontStyle = "normal"; public static final String defaultPosition = "absolute"; public static final String transparentColor = "rgba(0,0,0,0)"; private String units; //font private String fontFamily; private float fontSize; private String fontWeight; private String fontStyle; private float lineHeight; private float wordSpacing; private float letterSpacing; private String color; private String strokeColor; //position private String position; private float left; private float top; /** * Creates a new style using the specified units for lengths. * @param units Units used for lengths (e.g. 'pt') */ public BoxStyle(String units) { this.units = new String(units); fontFamily = null; fontSize = 0; fontWeight = null; fontStyle = null; lineHeight = 0; wordSpacing = 0; letterSpacing = 0; color = null; position = null; left = 0; top = 0; } public BoxStyle(BoxStyle src) { this.units = new String(src.units); fontFamily = src.fontFamily == null ? null : new String(src.fontFamily); fontSize = src.fontSize; fontWeight = src.fontWeight == null ? null : new String(src.fontWeight); fontStyle = src.fontStyle == null ? null : new String(src.fontStyle); lineHeight = src.lineHeight; wordSpacing = src.wordSpacing; letterSpacing = src.letterSpacing; color = src.color == null ? null : new String(src.color); position = src.position == null ? null : new String(src.position); left = src.left; top = src.top; strokeColor = src.strokeColor; } public String toString() { StringBuilder ret = new StringBuilder(); if (position != null && !position.equals(defaultPosition)) appendString(ret, "position", position); appendLength(ret, "top", top); appendLength(ret, "left", left); appendLength(ret, "line-height", lineHeight); if (fontFamily != null) appendString(ret, "font-family", fontFamily); if (fontSize != 0) appendLength(ret, "font-size", fontSize); if (fontWeight != null && !defaultFontWeight.equals(fontWeight)) appendString(ret, "font-weight", fontWeight); if (fontStyle != null && !defaultFontStyle.equals(fontStyle)) appendString(ret, "font-style", fontStyle); if (wordSpacing != 0) appendLength(ret, "word-spacing", wordSpacing); if (letterSpacing != 0) appendLength(ret, "letter-spacing", letterSpacing); if (color != null && !defaultColor.equals(color)) appendString(ret, "color", color); if (strokeColor != null && !strokeColor.equals(transparentColor)) ret.append(createTextStrokeCss(strokeColor)); return ret.toString(); } private void appendString(StringBuilder s, String propertyName, String value) { s.append(propertyName); s.append(':'); s.append(value); s.append(';'); } private void appendLength(StringBuilder s, String propertyName, float value) { s.append(propertyName); s.append(':'); s.append(formatLength(value)); s.append(';'); } public String formatLength(float length) { //return String.format(Locale.US, "%1.1f%s", length, units); //nice but slow return (float) length + units; } private String createTextStrokeCss(String color) { // text shadow fall back for non webkit, gets disabled in default style sheet // since can't use @media in inline styles String strokeCss = "-webkit-text-stroke: %color% 1px ;" + "text-shadow:" + "-1px -1px 0 %color%, " + "1px -1px 0 %color%," + "-1px 1px 0 %color%, " + "1px 1px 0 %color%;"; return strokeCss.replaceAll("%color%", color); } //================================================================ /** * @return the units */ public String getUnits() { return units; } /** * @param units the units to set */ public void setUnits(String units) { this.units = units; } /** * @return the fontFamily */ public String getFontFamily() { return fontFamily; } /** * @param fontFamily the fontFamily to set */ public void setFontFamily(String fontFamily) { this.fontFamily = fontFamily; } /** * @return the fontSize */ public float getFontSize() { return fontSize; } /** * @param fontSize the fontSize to set */ public void setFontSize(float fontSize) { this.fontSize = fontSize; } /** * @return the fontWeight */ public String getFontWeight() { return fontWeight; } /** * @param fontWeight the fontWeight to set */ public void setFontWeight(String fontWeight) { this.fontWeight = fontWeight; } /** * @return the fontStyle */ public String getFontStyle() { return fontStyle; } /** * @param fontStyle the fontStyle to set */ public void setFontStyle(String fontStyle) { this.fontStyle = fontStyle; } /** * @return the lineHeight */ public float getLineHeight() { return lineHeight; } /** * @param lineHeight the lineHeight to set */ public void setLineHeight(float lineHeight) { this.lineHeight = lineHeight; } /** * @return the wordSpacing */ public float getWordSpacing() { return wordSpacing; } /** * @param wordSpacing the wordSpacing to set */ public void setWordSpacing(float wordSpacing) { this.wordSpacing = wordSpacing; } /** * @return the letterSpacing */ public float getLetterSpacing() { return letterSpacing; } /** * @param letterSpacing the letterSpacing to set */ public void setLetterSpacing(float letterSpacing) { this.letterSpacing = letterSpacing; } /** * @return the color */ public String getColor() { return color; } /** * @param color the color to set */ public void setColor(String color) { this.color = color; } /** * @return the strokeColor */ public String getStrokeColor() { return strokeColor; } /** * @param strokeColor the strokeColor to set */ public void setStrokeColor(String strokeColor) { this.strokeColor = strokeColor; } /** * @return the left */ public float getLeft() { return left; } /** * @param left the left to set */ public void setLeft(float left) { this.left = left; } /** * @return the top */ public float getTop() { return top; } /** * @param top the top to set */ public void setTop(float top) { this.top = top; } //================================================================ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((color == null) ? 0 : color.hashCode()); result = prime * result + ((strokeColor == null) ? 0 : strokeColor.hashCode()); result = prime * result + ((fontFamily == null) ? 0 : fontFamily.hashCode()); result = prime * result + Float.floatToIntBits(fontSize); result = prime * result + ((fontStyle == null) ? 0 : fontStyle.hashCode()); result = prime * result + ((fontWeight == null) ? 0 : fontWeight.hashCode()); result = prime * result + Float.floatToIntBits(letterSpacing); result = prime * result + Float.floatToIntBits(wordSpacing); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BoxStyle other = (BoxStyle) obj; if (color == null) { if (other.color != null) return false; } else if (!color.equals(other.color)) return false; if (strokeColor == null) { if (other.strokeColor != null) return false; } else if (!strokeColor.equals(other.strokeColor)) return false; if (fontFamily == null) { if (other.fontFamily != null) return false; } else if (!fontFamily.equals(other.fontFamily)) return false; if (Float.floatToIntBits(fontSize) != Float .floatToIntBits(other.fontSize)) return false; if (fontStyle == null) { if (other.fontStyle != null) return false; } else if (!fontStyle.equals(other.fontStyle)) return false; if (fontWeight == null) { if (other.fontWeight != null) return false; } else if (!fontWeight.equals(other.fontWeight)) return false; if (Float.floatToIntBits(letterSpacing) != Float .floatToIntBits(other.letterSpacing)) return false; if (Float.floatToIntBits(wordSpacing) != Float .floatToIntBits(other.wordSpacing)) return false; return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/PathDrawer.java
released/MyBox/src/main/java/thridparty/pdfdom/PathDrawer.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.List; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState; import org.slf4j.Logger; import static org.slf4j.LoggerFactory.getLogger; public class PathDrawer { private static final Logger log = getLogger(PathDrawer.class); private final PDGraphicsState state; public PathDrawer(PDGraphicsState state) { this.state = state; } public ImageResource drawPath(List<PathSegment> path) throws IOException { if (path.size() == 0) { return new ImageResource("PathImage", new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)); } Rectangle2D.Double bounds = getPathBounds(path); if (bounds.getHeight() <= 0 || bounds.getWidth() <= 0) { bounds.width = bounds.height = 1; log.info("Filled curved paths are not yet supported by Pdf2Dom."); } BufferedImage image = new BufferedImage((int) bounds.getWidth(), (int) bounds.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D gfx = image.createGraphics(); try { clearPathGraphics(bounds, gfx); drawPathSegments(path, gfx); } catch (UnsupportedOperationException e) { log.info("Discarding unsupported path"); image = null; } gfx.dispose(); if (image != null) { // keep track of whitespace cropped off for html element positioning ImageResource drawnPath = new ImageResource("PathImage", image); drawnPath.setX(bounds.getX()); drawnPath.setY(bounds.getY()); return drawnPath; } else { return null; } } private void clearPathGraphics(Rectangle2D.Double bounds, Graphics2D gfx) throws IOException { Color transparent = new Color(255, 255, 255, 0); gfx.setColor(transparent); gfx.fillRect(0, 0, (int) bounds.getWidth() * 2, (int) bounds.getHeight() * 2); Color fill = pdfColorToColor(state.getNonStrokingColor()); Color stroke = pdfColorToColor(state.getStrokingColor()); // crop off rendered path whitespace gfx.translate(-bounds.getX(), -bounds.getY()); gfx.setPaint(stroke); gfx.setColor(fill); } private void drawPathSegments(List<PathSegment> path, Graphics2D gfx) { int[] xPts = new int[path.size()]; int[] yPts = new int[path.size()]; for (int i = 0; i < path.size(); i++) { PathSegment segmentOn = path.get(i); xPts[i] = (int) segmentOn.getX1(); yPts[i] = (int) segmentOn.getY1(); } gfx.fillPolygon(xPts, yPts, path.size()); } private Rectangle2D.Double getPathBounds(List<PathSegment> path) { PathSegment first = path.get(0); int minX = (int) first.getX1(), maxX = (int) first.getX1(); int minY = (int) first.getY2(), maxY = (int) first.getY1(); for (PathSegment segmentOn : path) { maxX = Math.max((int) segmentOn.getX1(), maxX); maxX = Math.max((int) segmentOn.getX2(), maxX); maxY = Math.max((int) segmentOn.getY1(), maxY); maxY = Math.max((int) segmentOn.getY2(), maxY); minX = Math.min((int) segmentOn.getX1(), minX); minX = Math.min((int) segmentOn.getX2(), minX); minY = Math.min((int) segmentOn.getY1(), minY); minY = Math.min((int) segmentOn.getY2(), minY); } int width = maxX - minX; int height = maxY - minY; int x = minX; int y = minY; return new Rectangle2D.Double(x, y, width, height); } private Color pdfColorToColor(PDColor color) throws IOException { float[] rgb = color.getColorSpace().toRGB(color.getComponents()); return new Color(rgb[0], rgb[1], rgb[2]); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/PDFBoxTree.java
released/MyBox/src/main/java/thridparty/pdfdom/PDFBoxTree.java
/** * PDFBoxTree.java * (c) Radek Burget, 2011 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 27.9.2011, 16:56:55 by burgetr */ package thridparty.pdfdom; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import mara.mybox.dev.MyBoxLog; import org.apache.pdfbox.contentstream.operator.Operator; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingColor; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingColorN; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingColorSpace; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingDeviceCMYKColor; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingDeviceGrayColor; import org.apache.pdfbox.contentstream.operator.color.SetNonStrokingDeviceRGBColor; import org.apache.pdfbox.contentstream.operator.color.SetStrokingColor; import org.apache.pdfbox.contentstream.operator.color.SetStrokingColorN; import org.apache.pdfbox.contentstream.operator.color.SetStrokingColorSpace; import org.apache.pdfbox.contentstream.operator.color.SetStrokingDeviceCMYKColor; import org.apache.pdfbox.contentstream.operator.color.SetStrokingDeviceGrayColor; import org.apache.pdfbox.contentstream.operator.color.SetStrokingDeviceRGBColor; import org.apache.pdfbox.contentstream.operator.state.SetFlatness; import org.apache.pdfbox.contentstream.operator.state.SetLineCapStyle; import org.apache.pdfbox.contentstream.operator.state.SetLineDashPattern; import org.apache.pdfbox.contentstream.operator.state.SetLineJoinStyle; import org.apache.pdfbox.contentstream.operator.state.SetLineMiterLimit; import org.apache.pdfbox.contentstream.operator.state.SetLineWidth; import org.apache.pdfbox.contentstream.operator.state.SetRenderingIntent; import org.apache.pdfbox.contentstream.operator.text.SetFontAndSize; import org.apache.pdfbox.cos.COSBase; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.cos.COSNumber; import org.apache.pdfbox.cos.COSString; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDResources; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.font.*; import org.apache.pdfbox.pdmodel.graphics.PDXObject; import org.apache.pdfbox.pdmodel.graphics.color.PDColor; import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode; import static org.apache.pdfbox.pdmodel.graphics.state.RenderingMode.*; import org.apache.pdfbox.text.PDFTextStripper; import org.apache.pdfbox.text.TextPosition; import org.apache.pdfbox.util.Matrix; /** * A generic tree of boxes created from a PDF file. It processes the PDF * document and calls the appropriate abstract methods in order to render a * page, text box, etc. The particular implementations are expected to implement * these actions in order to build the resulting document tree. * * @author burgetr * * Updated by Mara */ public abstract class PDFBoxTree extends PDFTextStripper { /** * Length units used in the generated CSS */ public static final String UNIT = "pt"; /** * Known font names that are recognized in the PDF files */ protected static String[] cssFontFamily = {"Times New Roman", "Times", "Garamond", "Helvetica", "Arial Narrow", "Arial", "Verdana", "Courier New", "MS Sans Serif"}; /** * Known font subtypes recognized in PDF files */ protected static String[] pdFontType = {"normal", "roman", "bold", "italic", "bolditalic"}; /** * Font weights corresponding to the font subtypes in * {@link PDFDomTree#pdFontType} */ protected static String[] cssFontWeight = {"normal", "normal", "bold", "normal", "bold"}; /** * Font styles corresponding to the font subtypes in * {@link PDFDomTree#pdFontType} */ protected static String[] cssFontStyle = {"normal", "normal", "normal", "italic", "italic"}; /** * When set to <code>true</code>, the graphics in the PDF file will be * ignored. */ protected boolean disableGraphics = false; /** * When set to <code>true</code>, the embedded images will be ignored. */ protected boolean disableImages = false; /** * When set to <code>true</code>, the image data will not be transferred to * the HTML data: url. */ protected boolean disableImageData = false; /** * First page to be processed */ protected int startPage; /** * Last page to be processed */ protected int endPage; /** * Table of embedded fonts */ protected FontTable fontTable; /** * The PDF page currently being processed */ protected PDPage pdpage; /** * Current text coordinates (the coordinates of the last encountered text * box). */ protected float cur_x; /** * Current text coordinates (the coordinates of the last encountered text * box). */ protected float cur_y; /** * Current path construction position */ protected float path_x; /** * Current path construction position */ protected float path_y; /** * Starting path construction position */ protected float path_start_x; /** * Starting path construction position */ protected float path_start_y; /** * Previous positioned text. */ protected TextPosition lastText = null; /** * Last diacritic if any */ protected TextPosition lastDia = null; /** * The text box currently being created. */ protected StringBuilder textLine; /** * Current text line metrics */ protected TextMetrics textMetrics; /** * Current graphics path */ protected Vector<PathSegment> graphicsPath; /** * The style of the future box being modified by the operators */ protected BoxStyle style; /** * The style of the text line being created */ protected BoxStyle curstyle; public PDFBoxTree() throws IOException { super(); super.setSortByPosition(true); super.setSuppressDuplicateOverlappingText(true); //add operators for tracking the graphic state addOperator(new SetStrokingColorSpace(this)); addOperator(new SetNonStrokingColorSpace(this)); addOperator(new SetLineDashPattern(this)); addOperator(new SetStrokingDeviceGrayColor(this)); addOperator(new SetNonStrokingDeviceGrayColor(this)); addOperator(new SetFlatness(this)); addOperator(new SetLineJoinStyle(this)); addOperator(new SetLineCapStyle(this)); addOperator(new SetStrokingDeviceCMYKColor(this)); addOperator(new SetNonStrokingDeviceCMYKColor(this)); addOperator(new SetLineMiterLimit(this)); addOperator(new SetStrokingDeviceRGBColor(this)); addOperator(new SetNonStrokingDeviceRGBColor(this)); addOperator(new SetRenderingIntent(this)); addOperator(new SetStrokingColor(this)); addOperator(new SetNonStrokingColor(this)); addOperator(new SetStrokingColorN(this)); addOperator(new SetNonStrokingColorN(this)); addOperator(new SetFontAndSize(this)); addOperator(new SetLineWidth(this)); init(); } /** * Internal initialization. */ private void init() { style = new BoxStyle(UNIT); textLine = new StringBuilder(); textMetrics = null; graphicsPath = new Vector<>(); startPage = 0; endPage = Integer.MAX_VALUE; fontTable = new FontTable(); } @Override public void processPage(PDPage page) { try { int p = this.getCurrentPageNo(); if (p >= startPage && p <= endPage) { pdpage = page; updateFontTable(); startNewPage(); super.processPage(page); finishBox(); } } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Checks whether the graphics processing is disabled. * * @return <code>true</code> when the graphics processing is disabled in the * parser configuration. */ public boolean getDisableGraphics() { return disableGraphics; } /** * Disables the processing of the graphic operators in the PDF files. * * @param disableGraphics when set to <code>true</code> the graphics is * ignored in the source file. */ public void setDisableGraphics(boolean disableGraphics) { this.disableGraphics = disableGraphics; } /** * Checks whether processing of embedded images is disabled. * * @return <code>true</code> when the processing of embedded images is * disabled in the parser configuration. */ public boolean getDisableImages() { return disableImages; } /** * Disables the processing of images contained in the PDF files. * * @param disableImages when set to <code>true</code> the images are ignored * in the source file. */ public void setDisableImages(boolean disableImages) { this.disableImages = disableImages; } /** * Checks whether the copying of image data is disabled. * * @return <code>true</code> when the copying of image data is disabled in * the parser configuration. */ public boolean getDisableImageData() { return disableImageData; } /** * Disables the copying the image data to the resulting DOM tree. * * @param disableImageData when set to <code>true</code> the image data is * not copied to the document tree. The eventual <code>img</code> elements * will have an empty <code>src</code> attribute. */ public void setDisableImageData(boolean disableImageData) { this.disableImageData = disableImageData; } @Override public int getStartPage() { return startPage; } @Override public void setStartPage(int startPage) { this.startPage = startPage; } @Override public int getEndPage() { return endPage; } @Override public void setEndPage(int endPage) { this.endPage = endPage; } //=========================================================================================== /** * Adds a new page to the resulting document and makes it a current (active) * page. */ protected abstract void startNewPage(); /** * Creates a new text box in the current page. The style and position of the * text are contained in the {@link PDFBoxTree#curstyle} property. * * @param data The text contents. */ protected abstract void renderText(String data, TextMetrics metrics); /** * Adds a rectangle to the current page on the specified position. * * @param rect the rectangle to be rendered * @param stroke should there be a stroke around? * @param fill should the rectangle be filled? */ protected abstract void renderPath(List<PathSegment> path, boolean stroke, boolean fill) throws IOException; /** * Adds an image to the current page. * * @param type the image type: <code>"png"</code> or <code>"jpeg"</code> * @param x the X coordinate of the image * @param y the Y coordinate of the image * @param width the width coordinate of the image * @param height the height coordinate of the image * @param data the image data depending on the specified type * @return */ protected abstract void renderImage(float x, float y, float width, float height, ImageResource data) throws IOException; protected float[] toRectangle(List<PathSegment> path) { if (path.size() == 4) { Set<Float> xc = new HashSet<Float>(); Set<Float> yc = new HashSet<Float>(); //find x/y 1/2 for (PathSegment line : path) { xc.add(line.getX1()); xc.add(line.getX2()); yc.add(line.getY1()); yc.add(line.getY2()); } if (xc.size() == 2 && yc.size() == 2) { return new float[]{Collections.min(xc), Collections.min(yc), Collections.max(xc), Collections.max(yc)}; } else { return null; //two different X and Y coordinates required } } else { return null; //four segments required } } /** * Updates the font table by adding new fonts used at the current page. */ protected void updateFontTable() { try { PDResources resources = pdpage.getResources(); if (resources != null) { processFontResources(resources, fontTable); } } catch (Exception e) { MyBoxLog.console(e.toString()); } } private void processFontResources(PDResources resources, FontTable table) { try { for (COSName key : resources.getFontNames()) { PDFont font = resources.getFont(key); if (font instanceof PDTrueTypeFont) { table.addEntry(font); } else if (font instanceof PDType0Font) { PDCIDFont descendantFont = ((PDType0Font) font).getDescendantFont(); if (descendantFont instanceof PDCIDFontType2) { table.addEntry(font); } else { // MyBoxLog.console("fontNotSupported: " + font.getName() + " " + font.getClass().getSimpleName()); } } else if (font instanceof PDType1CFont) { table.addEntry(font); } else { // MyBoxLog.console("fontNotSupported: " + font.getName() + " " + font.getClass().getSimpleName()); } } for (COSName name : resources.getXObjectNames()) { PDXObject xobject = resources.getXObject(name); if (xobject instanceof PDFormXObject) { PDFormXObject xObjectForm = (PDFormXObject) xobject; PDResources formResources = xObjectForm.getResources(); if (formResources != null && formResources != resources && formResources.getCOSObject() != resources.getCOSObject()) { processFontResources(formResources, table); } } } } catch (Exception e) { MyBoxLog.console(e.toString()); } } //=========================================================================================== @Override protected void processOperator(Operator operator, List<COSBase> arguments) { try { String operation = operator.getName(); /*System.out.println("Operator: " + operation + ":" + arguments.size()); if (operation.equals("sc") || operation.equals("cs")) { System.out.print(" "); for (int i = 0; i < arguments.size(); i++) System.out.print(arguments.get(i) + " "); System.out.println(); }*/ //word spacing if (operation.equals("Tw")) { style.setWordSpacing(getLength(arguments.get(0))); } //letter spacing else if (operation.equals("Tc")) { style.setLetterSpacing(getLength(arguments.get(0))); } //graphics else if (operation.equals("m")) //move { if (!disableGraphics) { if (arguments.size() == 2) { float[] pos = transformPosition(getLength(arguments.get(0)), getLength(arguments.get(1))); path_x = pos[0]; path_y = pos[1]; path_start_x = pos[0]; path_start_y = pos[1]; } } } else if (operation.equals("l")) //line { if (!disableGraphics) { if (arguments.size() == 2) { float[] pos = transformPosition(getLength(arguments.get(0)), getLength(arguments.get(1))); graphicsPath.add(new PathSegment(path_x, path_y, pos[0], pos[1])); path_x = pos[0]; path_y = pos[1]; } } } else if (operation.equals("h")) //end subpath { if (!disableGraphics) { graphicsPath.add(new PathSegment(path_x, path_y, path_start_x, path_start_y)); } } //rectangle else if (operation.equals("re")) { if (!disableGraphics) { if (arguments.size() == 4) { float x = getLength(arguments.get(0)); float y = getLength(arguments.get(1)); float width = getLength(arguments.get(2)); float height = getLength(arguments.get(3)); float[] p1 = transformPosition(x, y); float[] p2 = transformPosition(x + width, y + height); graphicsPath.add(new PathSegment(p1[0], p1[1], p2[0], p1[1])); graphicsPath.add(new PathSegment(p2[0], p1[1], p2[0], p2[1])); graphicsPath.add(new PathSegment(p2[0], p2[1], p1[0], p2[1])); graphicsPath.add(new PathSegment(p1[0], p2[1], p1[0], p1[1])); } } } //fill else if (operation.equals("f") || operation.equals("F") || operation.equals("f*")) { renderPath(graphicsPath, false, true); graphicsPath.removeAllElements(); } //stroke else if (operation.equals("S")) { renderPath(graphicsPath, true, false); graphicsPath.removeAllElements(); } else if (operation.equals("s")) { graphicsPath.add(new PathSegment(path_x, path_y, path_start_x, path_start_y)); renderPath(graphicsPath, true, false); graphicsPath.removeAllElements(); } //stroke and fill else if (operation.equals("B") || operation.equals("B*")) { renderPath(graphicsPath, true, true); graphicsPath.removeAllElements(); } else if (operation.equals("b") || operation.equals("b*")) { graphicsPath.add(new PathSegment(path_x, path_y, path_start_x, path_start_y)); renderPath(graphicsPath, true, true); graphicsPath.removeAllElements(); } //cancel path else if (operation.equals("n")) { graphicsPath.removeAllElements(); } //invoke named object - images else if (operation.equals("Do")) { if (!disableImages) { processImageOperation(arguments); } } super.processOperator(operator, arguments); } catch (Exception e) { MyBoxLog.console(e.toString()); } } protected void processImageOperation(List<COSBase> arguments) { try { COSName objectName = (COSName) arguments.get(0); PDXObject xobject = getResources().getXObject(objectName); if (xobject instanceof PDImageXObject) { PDImageXObject pdfImage = (PDImageXObject) xobject; BufferedImage outputImage = pdfImage.getImage(); outputImage = rotateImage(outputImage); ImageResource imageData = new ImageResource(getTitle(), outputImage); Rectangle2D bounds = calculateImagePosition(pdfImage); float x = (float) bounds.getX(); float y = (float) bounds.getY(); renderImage(x, y, (float) bounds.getWidth(), (float) bounds.getHeight(), imageData); } } catch (Exception e) { MyBoxLog.console(e.toString()); } } private BufferedImage rotateImage(BufferedImage outputImage) { try { // x, y and size are handled by css attributes but still need to rotate the image so pulling // only rotation out of the matrix so no giant whitespace offset from translations Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); AffineTransform tr = ctm.createAffineTransform(); double rotate = Math.atan2(tr.getShearY(), tr.getScaleY()) - Math.toRadians(pdpage.getRotation()); outputImage = ImageUtils.rotateImage(outputImage, rotate); return outputImage; } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } private Rectangle2D calculateImagePosition(PDImageXObject pdfImage) { try { Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Rectangle2D imageBounds = pdfImage.getImage().getRaster().getBounds(); AffineTransform imageTransform = new AffineTransform(ctm.createAffineTransform()); imageTransform.scale(1.0 / pdfImage.getWidth(), -1.0 / pdfImage.getHeight()); imageTransform.translate(0, -pdfImage.getHeight()); AffineTransform pageTransform = createCurrentPageTransformation(); pageTransform.concatenate(imageTransform); return pageTransform.createTransformedShape(imageBounds).getBounds2D(); } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } @Override protected void processTextPosition(TextPosition text) { try { if (text.isDiacritic()) { lastDia = text; } else if (!text.getUnicode().trim().isEmpty()) { if (lastDia != null) { if (text.contains(lastDia)) { text.mergeDiacritic(lastDia); } lastDia = null; } /*float[] c = transformPosition(text.getX(), text.getY()); cur_x = c[0]; cur_y = c[1];*/ cur_x = text.getX(); cur_y = text.getY(); /*System.out.println("Text: " + text.getCharacter()); System.out.println(" Font size: " + text.getFontSize() + " " + text.getFontSizeInPt() + "pt"); System.out.println(" Width: " + text.getWidth()); System.out.println(" Width adj: " + text.getWidthDirAdj()); System.out.println(" Height: " + text.getHeight()); System.out.println(" Height dir: " + text.getHeightDir()); System.out.println(" XScale: " + text.getXScale()); System.out.println(" YScale: " + text.getYScale());*/ float distx = 0; float disty = 0; if (lastText != null) { distx = text.getX() - (lastText.getX() + lastText.getWidth()); disty = text.getY() - lastText.getY(); } //should we split the boxes? boolean split = lastText == null || distx > 1.0f || distx < -6.0f || Math.abs(disty) > 1.0f || isReversed(getTextDirectionality(text)) != isReversed(getTextDirectionality(lastText)); //if the style changed, we should split the boxes updateStyle(style, text); if (!style.equals(curstyle)) { split = true; } if (split) //start of a new box { //finish current box (if any) if (lastText != null) { finishBox(); } //start a new box curstyle = new BoxStyle(style); } textLine.append(text.getUnicode()); if (textMetrics == null) { textMetrics = new TextMetrics(text); } else { textMetrics.append(text); } lastText = text; } } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Finishes the current box - empties the text line buffer and creates a DOM * element from it. */ protected void finishBox() { try { if (textLine.length() > 0) { String s; if (isReversed(Character.getDirectionality(textLine.charAt(0)))) { s = textLine.reverse().toString(); } else { s = textLine.toString(); } curstyle.setLeft(textMetrics.getX()); curstyle.setTop(textMetrics.getTop()); curstyle.setLineHeight(textMetrics.getHeight()); renderText(s, textMetrics); textLine = new StringBuilder(); textMetrics = null; } } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Checks whether the text directionality corresponds to reversed text (very * rough) * * @param directionality the Character.directionality * @return */ protected boolean isReversed(byte directionality) { try { switch (directionality) { case Character.DIRECTIONALITY_RIGHT_TO_LEFT: case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC: case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING: case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE: return true; } } catch (Exception e) { MyBoxLog.console(e.toString()); } return false; } /** * Updates the text style according to a new text position * * @param bstyle the style to be updated * @param text the text position */ protected void updateStyle(BoxStyle bstyle, TextPosition text) { try { String font = text.getFont().getName(); String family = null; String weight = null; String fstyle = null; bstyle.setFontSize(text.getXScale()); //this seems to give better results than getFontSizeInPt() bstyle.setLineHeight(text.getHeight()); if (font != null) { //font style and weight for (int i = 0; i < pdFontType.length; i++) { if (font.toLowerCase().lastIndexOf(pdFontType[i]) >= 0) { weight = cssFontWeight[i]; fstyle = cssFontStyle[i]; break; } } if (weight != null) { bstyle.setFontWeight(weight); } else { bstyle.setFontWeight(cssFontWeight[0]); } if (fstyle != null) { bstyle.setFontStyle(fstyle); } else { bstyle.setFontStyle(cssFontStyle[0]); } //font family //If it's a known common font don't embed in html output to save space String knownFontFamily = findKnownFontFamily(font); if (!knownFontFamily.equals("")) { family = knownFontFamily; } else { family = fontTable.getUsedName(text.getFont()); if (family == null) { family = font; } } if (family != null) { bstyle.setFontFamily(family); } } updateStyleForRenderingMode(); } catch (Exception e) { MyBoxLog.console(e.toString()); } } private String findKnownFontFamily(String font) { try { for (String fontFamilyOn : cssFontFamily) { if (font.toLowerCase().lastIndexOf(fontFamilyOn.toLowerCase().replaceAll("\\s+", "")) >= 0) { return fontFamilyOn; } } } catch (Exception e) { MyBoxLog.console(e.toString()); } return ""; } private void updateStyleForRenderingMode() { try { String fillColor = colorString(getGraphicsState().getNonStrokingColor()); String strokeColor = colorString(getGraphicsState().getStrokingColor()); if (isTextFillEnabled()) { style.setColor(fillColor); } else { style.setColor(BoxStyle.transparentColor); } if (isTextStrokeEnabled()) { style.setStrokeColor(strokeColor); } else { style.setStrokeColor(BoxStyle.transparentColor); } } catch (Exception e) { MyBoxLog.console(e.toString()); } } private boolean isTextStrokeEnabled() { RenderingMode mode = getGraphicsState().getTextState().getRenderingMode(); return mode == STROKE || mode == STROKE_CLIP || mode == FILL_STROKE || mode == FILL_STROKE_CLIP; } private boolean isTextFillEnabled() { RenderingMode mode = getGraphicsState().getTextState().getRenderingMode(); return mode == FILL || mode == FILL_CLIP || mode == FILL_STROKE || mode == FILL_STROKE_CLIP; } /** * Obtains the media box valid for the current page. * * @return the media box rectangle */ protected PDRectangle getCurrentMediaBox() { PDRectangle layout = pdpage.getCropBox(); return layout; } //=========================================================================================== /** * Transforms a length according to the current transformation matrix. */ protected float transformLength(float w) { Matrix ctm = getGraphicsState().getCurrentTransformationMatrix(); Matrix m = new Matrix(); m.setValue(2, 0, w); return m.multiply(ctm).getTranslateX(); } /** * Transforms a position according to the current transformation matrix and * current page transformation. * * @param x * @param y * @return */ protected float[] transformPosition(float x, float y) { Point2D.Float point = super.transformedPoint(x, y); AffineTransform pageTransform = createCurrentPageTransformation(); Point2D.Float transformedPoint = (Point2D.Float) pageTransform.transform(point, null); return new float[]{(float) transformedPoint.getX(), (float) transformedPoint.getY()}; } protected AffineTransform createCurrentPageTransformation() { PDRectangle cb = pdpage.getCropBox(); AffineTransform pageTransform = new AffineTransform(); switch (pdpage.getRotation()) { case 90: pageTransform.translate(cb.getHeight(), 0); break; case 180: pageTransform.translate(cb.getWidth(), cb.getHeight()); break; case 270: pageTransform.translate(0, cb.getWidth()); break; } pageTransform.rotate(Math.toRadians(pdpage.getRotation())); pageTransform.translate(0, cb.getHeight()); pageTransform.scale(1, -1);
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/EmbedAsBase64Handler.java
released/MyBox/src/main/java/thridparty/pdfdom/EmbedAsBase64Handler.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.IOException; public class EmbedAsBase64Handler implements HtmlResourceHandler { public String handleResource(HtmlResource resource) throws IOException { char[] base64Data = new char[0]; byte[] data = resource.getData(); if (data != null) base64Data = Base64Coder.encode(data); return String.format("data:%s;base64,%s", resource.getMimeType(), new String(base64Data)); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/ImageResource.java
released/MyBox/src/main/java/thridparty/pdfdom/ImageResource.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; public class ImageResource extends HtmlResource { private final BufferedImage image; private double x = 0; private double y = 0; public ImageResource(String name, BufferedImage image) { super(name); this.image = image; } public byte[] getData() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", buffer); return buffer.toByteArray(); } public String getFileEnding() { return "png"; } public String getMimeType() { return "image/png"; } public void setX(double x) { this.x = x; } public double getX() { return x; } public void setY(double y) { this.y = y; } public double getY() { return y; } public float getHeight() { return image.getHeight(); } public float getWidth() { return image.getWidth(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/Base64Coder.java
released/MyBox/src/main/java/thridparty/pdfdom/Base64Coder.java
package thridparty.pdfdom; /** * A Base64 Encoder/Decoder. * * <p> * This class is used to encode and decode data in Base64 format as described in RFC 1521. * * <p> * This is "Open Source" software and released under the <a href="http://www.gnu.org/licenses/lgpl.html">GNU/LGPL</a> license.<br> * It is provided "as is" without warranty of any kind.<br> * Copyright 2003: Christian d'Heureuse, Inventec Informatik AG, Switzerland.<br> * Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br> * * <p> * Version history:<br> * 2003-07-22 Christian d'Heureuse (chdh): Module created.<br> * 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br> * 2006-11-21 chdh:<br> * &nbsp; Method encode(String) renamed to encodeString(String).<br> * &nbsp; Method decode(String) renamed to decodeString(String).<br> * &nbsp; New method encode(byte[],int) added.<br> * &nbsp; New method decode(String) added.<br> */ public class Base64Coder { // Mapping table from 6-bit nibbles to Base64 characters. private static char[] map1 = new char[64]; static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } // Mapping table from Base64 characters to 6-bit nibbles. private static byte[] map2 = new byte[128]; static { for (int i=0; i<map2.length; i++) map2[i] = -1; for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; } /** * Encodes a string into Base64 format. * No blanks or line breaks are inserted. * @param s a String to be encoded. * @return A String with the Base64 encoded data. */ public static String encodeString (String s) { return new String(encode(s.getBytes())); } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted. * @param in an array containing the data bytes to be encoded. * @return A character array with the Base64 encoded data. */ public static char[] encode (byte[] in) { return encode(in,in.length); } /** * Encodes a byte array into Base64 format. * No blanks or line breaks are inserted. * @param in an array containing the data bytes to be encoded. * @param iLen number of bytes to process in <code>in</code>. * @return A character array with the Base64 encoded data. */ public static char[] encode (byte[] in, int iLen) { int oDataLen = (iLen*4+2)/3; // output length without padding int oLen = ((iLen+2)/3)*4; // output length including padding char[] out = new char[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++] & 0xff; int i1 = ip < iLen ? in[ip++] & 0xff : 0; int i2 = ip < iLen ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } /** * Decodes a string from Base64 format. * @param s a Base64 String to be decoded. * @return A String containing the decoded data. * @throws IllegalArgumentException if the input is not valid Base64 encoded data. */ public static String decodeString (String s) { return new String(decode(s)); } /** * Decodes a byte array from Base64 format. * @param s a Base64 String to be decoded. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException if the input is not valid Base64 encoded data. */ public static byte[] decode (String s) { return decode(s.toCharArray()); } /** * Decodes a byte array from Base64 format. * No blanks or line breaks are allowed within the Base64 encoded data. * @param in a character array containing the Base64 encoded data. * @return An array containing the decoded data bytes. * @throws IllegalArgumentException if the input is not valid Base64 encoded data. */ public static byte[] decode (char[] in) { int iLen = in.length; if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iLen-1] == '=') iLen--; int oLen = (iLen*3) / 4; byte[] out = new byte[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iLen ? in[ip++] : 'A'; int i3 = ip < iLen ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int o0 = ( b0 <<2) | (b1>>>4); int o1 = ((b1 & 0xf)<<4) | (b2>>>2); int o2 = ((b2 & 3)<<6) | b3; out[op++] = (byte)o0; if (op<oLen) out[op++] = (byte)o1; if (op<oLen) out[op++] = (byte)o2; } return out; } // Dummy constructor. private Base64Coder() {} } // end class Base64Coder
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/HtmlResourceHandler.java
released/MyBox/src/main/java/thridparty/pdfdom/HtmlResourceHandler.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.IOException; public interface HtmlResourceHandler { /** * @param data name for the resource * @param resourceName resource data * @return the URI to be used in generated HTML resource elements/ */ String handleResource(HtmlResource resource) throws IOException; }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/ImageUtils.java
released/MyBox/src/main/java/thridparty/pdfdom/ImageUtils.java
package thridparty.pdfdom; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; class ImageUtils { public static BufferedImage rotateImage(BufferedImage image, double theta) { int degrees = (int) Math.abs(Math.toDegrees(theta)); double xCenter = image.getWidth() / 2; double yCenter = image.getHeight() / 2; AffineTransform rotateTransform = AffineTransform.getRotateInstance(-theta, xCenter, yCenter); // Translation adjustments so image still centered after rotate width/height changes if (image.getHeight() != image.getWidth() && degrees != 180 && degrees != 0) { Point2D origin = new Point2D.Double(0.0, 0.0); origin = rotateTransform.transform(origin, null); double yTranslate = origin.getY(); Point2D yMax = new Point2D.Double(0, image.getHeight()); yMax = rotateTransform.transform(yMax, null); double xTranslate = yMax.getX(); AffineTransform translationAdjustment = AffineTransform.getTranslateInstance(-xTranslate, -yTranslate); rotateTransform.preConcatenate(translationAdjustment); } AffineTransformOp op = new AffineTransformOp(rotateTransform, AffineTransformOp.TYPE_BILINEAR); // Have to recopy image because of JDK bug #4723021, AffineTransformationOp throwing exception sometimes image = copyImage(image, BufferedImage.TYPE_INT_ARGB); // Need to create filter dest image ourselves since AffineTransformOp's own dest image creation // throws exceptions in some cases. Rectangle bounds = op.getBounds2D(image).getBounds(); BufferedImage finalImage = new BufferedImage((int) bounds.getWidth(), (int) bounds.getHeight(), BufferedImage.TYPE_INT_ARGB); return op.filter(image, finalImage); } public static BufferedImage copyImage(BufferedImage source, int type) { BufferedImage copy = new BufferedImage(source.getWidth(), source.getHeight(), type); Graphics gfx = copy.getGraphics(); gfx.drawImage(source, 0, 0, null); gfx.dispose(); return copy; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/PDFDomTree.java
released/MyBox/src/main/java/thridparty/pdfdom/PDFDomTree.java
/** * PDFDomTree.java * (c) Radek Burget, 2011 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 13.9.2011, 14:17:24 by burgetr */ package thridparty.pdfdom; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import mara.mybox.dev.MyBoxLog; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.Text; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSSerializer; /** * A DOM representation of a PDF file. * * @author burgetr * * Updated by Mara */ public class PDFDomTree extends PDFBoxTree { /** * Default style placed in the begining of the resulting document */ protected String defaultStyle = ".page{position:relative; border:1px solid blue;margin:0.5em}\n" + ".p,.r{position:absolute;}\n" + ".p{white-space:nowrap;}\n" + // disable text-shadow fallback for text stroke if stroke supported by browser "@supports(-webkit-text-stroke: 1px black) {" + ".p{text-shadow:none !important;}" + "}"; /** * The resulting document representing the PDF file. */ protected Document doc; /** * The head element of the resulting document. */ protected Element head; /** * The body element of the resulting document. */ protected Element body; /** * The title element of the resulting document. */ protected Element title; /** * The global style element of the resulting document. */ protected Element globalStyle; /** * The element representing the page currently being created in the * resulting document. */ protected Element curpage; /** * Text element counter for assigning IDs to the text elements. */ protected int textcnt; /** * Page counter for assigning IDs to the pages. */ protected int pagecnt; protected PDFDomTreeConfig config; /** * Creates a new PDF DOM parser. * * @throws IOException */ public PDFDomTree() throws IOException { super(); init(); } /** * Creates a new PDF DOM parser. * * @param config * @throws IOException */ public PDFDomTree(PDFDomTreeConfig config) throws IOException { this(); if (config != null) { this.config = config; } } /** * Internal initialization. */ private void init() { pagecnt = 0; textcnt = 0; this.config = PDFDomTreeConfig.createDefaultConfig(); } /** * Creates a new empty HTML document tree. */ protected void createDocument() { try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); DocumentType doctype = builder.getDOMImplementation().createDocumentType("html", "-//W3C//DTD XHTML 1.1//EN", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"); doc = builder.getDOMImplementation().createDocument("http://www.w3.org/1999/xhtml", "html", doctype); head = doc.createElement("head"); Element meta = doc.createElement("meta"); meta.setAttribute("http-equiv", "content-type"); meta.setAttribute("content", "text/html;charset=utf-8"); head.appendChild(meta); title = doc.createElement("title"); title.setTextContent("PDF Document"); head.appendChild(title); globalStyle = doc.createElement("style"); globalStyle.setAttribute("type", "text/css"); //globalStyle.setTextContent(createGlobalStyle()); head.appendChild(globalStyle); body = doc.createElement("body"); Element root = doc.getDocumentElement(); root.appendChild(head); root.appendChild(body); } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Obtains the resulting document tree. * * @return The DOM root element. */ public Document getDocument() { return doc; } @Override public void startDocument(PDDocument document) { createDocument(); } @Override protected void endDocument(PDDocument document) { try { //use the PDF title String doctitle = document.getDocumentInformation().getTitle(); if (doctitle != null && doctitle.trim().length() > 0) { title.setTextContent(doctitle); } //set the main style globalStyle.setTextContent(createGlobalStyle()); } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Parses a PDF document and serializes the resulting DOM tree to an output. * This requires a DOM Level 3 capable implementation to be available. */ @Override public void writeText(PDDocument doc, Writer outputStream) { try { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", true); LSOutput lsOutput = impl.createLSOutput(); lsOutput.setCharacterStream(outputStream); createDOM(doc); writer.write(getDocument(), lsOutput); } catch (Exception e) { MyBoxLog.console(e.toString()); } } /** * Loads a PDF document and creates a DOM tree from it. * * @param doc the source document * @return a DOM Document representing the DOM tree */ public Document createDOM(PDDocument doc) { try { /* We call the original PDFTextStripper.writeText but nothing should be printed actually because our processing methods produce no output. They create the DOM structures instead */ super.writeText(doc, new OutputStreamWriter(System.out)); return this.doc; } catch (Exception e) { MyBoxLog.console(e.toString()); return null; } } //=========================================================================================== @Override protected void startNewPage() { try { curpage = createPageElement(); body.appendChild(curpage); } catch (Exception e) { MyBoxLog.console(e.toString()); } } @Override protected void renderText(String data, TextMetrics metrics) { try { curpage.appendChild(createTextElement(data, metrics.getWidth())); } catch (Exception e) { MyBoxLog.console(e.toString()); } } @Override protected void renderPath(List<PathSegment> path, boolean stroke, boolean fill) throws IOException { float[] rect = toRectangle(path); if (rect != null) { curpage.appendChild(createRectangleElement(rect[0], rect[1], rect[2] - rect[0], rect[3] - rect[1], stroke, fill)); } else if (stroke) { for (PathSegment segm : path) { curpage.appendChild(createLineElement(segm.getX1(), segm.getY1(), segm.getX2(), segm.getY2())); } } else { Element pathImage = createPathImage(path); if (pathImage != null) { curpage.appendChild(pathImage); } } } @Override protected void renderImage(float x, float y, float width, float height, ImageResource resource) throws IOException { curpage.appendChild(createImageElement(x, y, width, height, resource)); } //=========================================================================================== /** * Creates an element that represents a single page. * * @return the resulting DOM element */ protected Element createPageElement() { String pstyle = ""; PDRectangle layout = getCurrentMediaBox(); if (layout != null) { /*System.out.println("x1 " + layout.getLowerLeftX()); System.out.println("y1 " + layout.getLowerLeftY()); System.out.println("x2 " + layout.getUpperRightX()); System.out.println("y2 " + layout.getUpperRightY()); System.out.println("rot " + pdpage.findRotation());*/ float w = layout.getWidth(); float h = layout.getHeight(); final int rot = pdpage.getRotation(); if (rot == 90 || rot == 270) { float x = w; w = h; h = x; } pstyle = "width:" + w + UNIT + ";" + "height:" + h + UNIT + ";"; pstyle += "overflow:hidden;"; } else { MyBoxLog.console("No media box found"); } Element el = doc.createElement("div"); el.setAttribute("id", "page_" + (pagecnt++)); el.setAttribute("class", "page"); el.setAttribute("style", pstyle); return el; } /** * Creates an element that represents a single positioned box with no * content. * * @return the resulting DOM element */ protected Element createTextElement(float width) { Element el = doc.createElement("div"); el.setAttribute("id", "p" + (textcnt++)); el.setAttribute("class", "p"); String style = curstyle.toString(); style += "width:" + width + UNIT + ";"; el.setAttribute("style", style); return el; } /** * Creates an element that represents a single positioned box containing the * specified text string. * * @param data the text string to be contained in the created box. * @return the resulting DOM element */ protected Element createTextElement(String data, float width) { Element el = createTextElement(width); Text text = doc.createTextNode(data); el.appendChild(text); return el; } /** * Creates an element that represents a rectangle drawn at the specified * coordinates in the page. * * @param x the X coordinate of the rectangle * @param y the Y coordinate of the rectangle * @param width the width of the rectangle * @param height the height of the rectangle * @param stroke should there be a stroke around? * @param fill should the rectangle be filled? * @return the resulting DOM element */ protected Element createRectangleElement(float x, float y, float width, float height, boolean stroke, boolean fill) { float lineWidth = transformWidth(getGraphicsState().getLineWidth()); float wcor = stroke ? lineWidth : 0.0f; float strokeOffset = wcor == 0 ? 0 : wcor / 2; width = width - wcor < 0 ? 1 : width - wcor; height = height - wcor < 0 ? 1 : height - wcor; StringBuilder pstyle = new StringBuilder(50); pstyle.append("left:").append(style.formatLength(x - strokeOffset)).append(';'); pstyle.append("top:").append(style.formatLength(y - strokeOffset)).append(';'); pstyle.append("width:").append(style.formatLength(width)).append(';'); pstyle.append("height:").append(style.formatLength(height)).append(';'); if (stroke) { String color = colorString(getGraphicsState().getStrokingColor()); pstyle.append("border:").append(style.formatLength(lineWidth)).append(" solid ").append(color).append(';'); } if (fill) { String fcolor = colorString(getGraphicsState().getNonStrokingColor()); pstyle.append("background-color:").append(fcolor).append(';'); } Element el = doc.createElement("div"); el.setAttribute("class", "r"); el.setAttribute("style", pstyle.toString()); el.appendChild(doc.createEntityReference("nbsp")); return el; } /** * Create an element that represents a horizntal or vertical line. * * @param x1 * @param y1 * @param x2 * @param y2 * @return the created DOM element */ protected Element createLineElement(float x1, float y1, float x2, float y2) { HtmlDivLine line = new HtmlDivLine(x1, y1, x2, y2, transformWidth(getGraphicsState().getLineWidth())); String color = colorString(getGraphicsState().getStrokingColor()); StringBuilder pstyle = new StringBuilder(50); pstyle.append("left:").append(style.formatLength(line.getLeft())).append(';'); pstyle.append("top:").append(style.formatLength(line.getTop())).append(';'); pstyle.append("width:").append(style.formatLength(line.getWidth())).append(';'); pstyle.append("height:").append(style.formatLength(line.getHeight())).append(';'); pstyle.append(line.getBorderSide()).append(':').append(style.formatLength(line.getLineStrokeWidth())).append(" solid ").append(color).append(';'); if (line.getAngleDegrees() != 0) { pstyle.append("transform:").append("rotate(").append(line.getAngleDegrees()).append("deg);"); } Element el = doc.createElement("div"); el.setAttribute("class", "r"); el.setAttribute("style", pstyle.toString()); el.appendChild(doc.createEntityReference("nbsp")); return el; } protected Element createPathImage(List<PathSegment> path) throws IOException { PathDrawer drawer = new PathDrawer(getGraphicsState()); ImageResource renderedPath = drawer.drawPath(path); if (renderedPath != null) { return createImageElement((float) renderedPath.getX(), (float) renderedPath.getY(), renderedPath.getWidth(), renderedPath.getHeight(), renderedPath); } else { return null; } } /** * Creates an element that represents an image drawn at the specified * coordinates in the page. * * @param x the X coordinate of the image * @param y the Y coordinate of the image * @param width the width coordinate of the image * @param height the height coordinate of the image * @param type the image type: <code>"png"</code> or <code>"jpeg"</code> * @param resource the image data depending on the specified type * @return */ protected Element createImageElement(float x, float y, float width, float height, ImageResource resource) throws IOException { StringBuilder pstyle = new StringBuilder("position:absolute;"); pstyle.append("left:").append(x).append(UNIT).append(';'); pstyle.append("top:").append(y).append(UNIT).append(';'); pstyle.append("width:").append(width).append(UNIT).append(';'); pstyle.append("height:").append(height).append(UNIT).append(';'); //pstyle.append("border:1px solid red;"); Element el = doc.createElement("img"); el.setAttribute("style", pstyle.toString()); String imgSrc = config.getImageHandler().handleResource(resource); if (!disableImageData && !imgSrc.isEmpty()) { el.setAttribute("src", imgSrc); } else { el.setAttribute("src", ""); } return el; } /** * Generate the global CSS style for the whole document. * * @return the CSS code used in the generated document header */ protected String createGlobalStyle() { StringBuilder ret = new StringBuilder(); ret.append(createFontFaces()); ret.append("\n"); ret.append(defaultStyle); return ret.toString(); } @Override protected void updateFontTable() { // skip font processing completley if ignore fonts mode to optimize processing speed if (!(config.getFontHandler() instanceof IgnoreResourceHandler)) { super.updateFontTable(); } } protected String createFontFaces() { StringBuilder ret = new StringBuilder(); for (FontTable.Entry font : fontTable.getEntries()) { createFontFace(ret, font); } return ret.toString(); } private void createFontFace(StringBuilder ret, FontTable.Entry font) { try { final String src = config.getFontHandler().handleResource(font); if (src != null && !src.trim().isEmpty()) { ret.append("@font-face {"); ret.append("font-family:\"").append(font.usedName).append("\";"); ret.append("src:url('"); ret.append(src); ret.append("');"); ret.append("}\n"); } } catch (IOException e) { MyBoxLog.console("Error writing font face data for font: " + font.getName() + "Exception: " + e.getMessage() + "\n" + e.getClass() ); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/PathSegment.java
released/MyBox/src/main/java/thridparty/pdfdom/PathSegment.java
/** * SubPath.java * (c) Radek Burget, 2015 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 9.9.2015, 15:27:27 by burgetr */ package thridparty.pdfdom; /** * @author burgetr * */ public class PathSegment { private float x1, y1, x2, y2; public PathSegment(float x1, float y1, float x2, float y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public float getX1() { return x1; } public void setX1(float x1) { this.x1 = x1; } public float getY1() { return y1; } public void setY1(float y1) { this.y1 = y1; } public float getX2() { return x2; } public void setX2(float x2) { this.x2 = x2; } public float getY2() { return y2; } public void setY2(float y2) { this.y2 = y2; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/PDFToHTML.java
released/MyBox/src/main/java/thridparty/pdfdom/PDFToHTML.java
/** * PDFToHTML.java * (c) Radek Burget, 2011 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. * * Created on 19.9.2011, 13:34:54 by burgetr */ package thridparty.pdfdom; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; /** * @author burgetr * */ public class PDFToHTML { public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: PDFToHTML <infile> [<outfile>] [<options>]"); System.out.println("Options: "); System.out.println("-fm=[mode] Font handler mode. [mode] = EMBED_BASE64, SAVE_TO_DIR, IGNORE"); System.out.println("-fdir=[path] Directory to extract fonts to. [path] = font extract directory ie dir/my-font-dir"); System.out.println(); System.out.println("-im=[mode] Image handler mode. [mode] = EMBED_BASE64, SAVE_TO_DIR, IGNORE"); System.out.println("-idir=[path] Directory to extract images to. [path] = image extract directory ie dir/my-image-dir"); System.exit(1); } String infile = args[0]; String outfile; if (args.length > 1 && !args[1].startsWith("-")) { outfile = args[1]; } else { String base = args[0]; if (base.toLowerCase().endsWith(".pdf")) { base = base.substring(0, base.length() - 4); } outfile = base + ".html"; } PDFDomTreeConfig config = parseOptions(args); PDDocument document = null; try { document = Loader.loadPDF(new File(infile)); PDFDomTree parser = new PDFDomTree(config); //parser.setDisableImageData(true); Writer output = new PrintWriter(outfile, "utf-8"); parser.writeText(document, output); output.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } finally { if (document != null) { try { document.close(); } catch (IOException e) { System.err.println("Error: " + e.getMessage()); //e.printStackTrace(); } } } } private static PDFDomTreeConfig parseOptions(String[] args) { PDFDomTreeConfig config = PDFDomTreeConfig.createDefaultConfig(); List<CommandLineFlag> flags = parseFlags(args); for (CommandLineFlag flagOn : flags) { if (flagOn.flagName.equals("fm")) { HtmlResourceHandler handler = createResourceHandlerFor(flagOn.value); config.setFontHandler(handler); } else if (flagOn.flagName.equals("fdir")) { config.setFontHandler(new SaveResourceToDirHandler(new File(flagOn.value))); } else if (flagOn.flagName.equals("im")) { HtmlResourceHandler handler = createResourceHandlerFor(flagOn.value); config.setImageHandler(handler); } else if (flagOn.flagName.equals("idir")) { config.setImageHandler(new SaveResourceToDirHandler(new File(flagOn.value))); } } return config; } private static HtmlResourceHandler createResourceHandlerFor(String value) { HtmlResourceHandler handler = PDFDomTreeConfig.embedAsBase64(); if (value.equalsIgnoreCase("EMBED_BASE64")) { handler = PDFDomTreeConfig.embedAsBase64(); } else if (value.equalsIgnoreCase("SAVE_TO_DIR")) { handler = new SaveResourceToDirHandler(); } else if (value.equalsIgnoreCase("IGNORE")) { handler = new IgnoreResourceHandler(); } return handler; } private static List<CommandLineFlag> parseFlags(String[] args) { List<CommandLineFlag> flags = new ArrayList<CommandLineFlag>(); for (String argOn : args) { if (argOn.startsWith("-")) { flags.add(CommandLineFlag.parse(argOn)); } } return flags; } private static class CommandLineFlag { public String flagName; public String value = ""; public static CommandLineFlag parse(String argOn) { CommandLineFlag flag = new CommandLineFlag(); String[] flagSplit = argOn.split("="); flag.flagName = flagSplit[0].replace("-", ""); if (flagSplit.length > 1) { flag.value = flagSplit[1].replace("=", ""); } return flag; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/HtmlResource.java
released/MyBox/src/main/java/thridparty/pdfdom/HtmlResource.java
/* * Copyright (c) Matthew Abboud 2016 * * Pdf2Dom is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pdf2Dom is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with CSSBox. If not, see <http://www.gnu.org/licenses/>. */ package thridparty.pdfdom; import java.io.IOException; public abstract class HtmlResource { protected String name; public HtmlResource(String name) { this.name = name; } public abstract byte[] getData() throws IOException; public abstract String getFileEnding(); public abstract String getMimeType(); public String getName() { return name; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/thridparty/pdfdom/TextMetrics.java
released/MyBox/src/main/java/thridparty/pdfdom/TextMetrics.java
package thridparty.pdfdom; import java.io.IOException; import org.apache.fontbox.util.BoundingBox; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.text.TextPosition; public class TextMetrics { private float x, baseline, width, height, pointSize, descent, ascent, fontSize; private PDFont font; public TextMetrics(TextPosition tp) { x = tp.getX(); baseline = tp.getY(); font = tp.getFont(); width = tp.getWidth(); height = tp.getHeight(); pointSize = tp.getFontSizeInPt(); fontSize = tp.getYScale(); ascent = getAscent(); descent = getDescent(); } public void append(TextPosition tp) { width += tp.getX() - (x + width) + tp.getWidth(); height = Math.max(height, tp.getHeight()); ascent = Math.max(ascent, getAscent(tp.getFont(), tp.getYScale())); descent = Math.min(descent, getDescent(tp.getFont(), tp.getYScale())); } public float getX() { return x; } public float getTop() { if (ascent != 0) return baseline - ascent; else return baseline - getBoundingBoxAscent(); } public float getBottom() { if (descent != 0) return baseline - descent; else return baseline - getBoundingBoxDescent(); } public float getBaseline() { return baseline; } public float getAscent() { return getAscent(font, fontSize); } public float getDescent() { final float descent = getDescent(font, fontSize); return descent > 0 ? -descent : descent; //positive descent is not allowed } public float getBoundingBoxDescent() { return getBoundingBoxDescent(font, fontSize); } public float getBoundingBoxAscent() { return getBoundingBoxAscent(font, fontSize); } public static float getBoundingBoxDescent(PDFont font, float fontSize) { try { BoundingBox bBox = font.getBoundingBox(); float boxDescent = bBox.getLowerLeftY(); return (boxDescent / 1000) * fontSize; } catch (IOException e) { } return 0.0f; } public static float getBoundingBoxAscent(PDFont font, float fontSize) { try { BoundingBox bBox = font.getBoundingBox(); float boxAscent = bBox.getUpperRightY(); return (boxAscent / 1000) * fontSize; } catch (IOException e) { } return 0.0f; } private static float getAscent(PDFont font, float fontSize) { try { return (font.getFontDescriptor().getAscent() / 1000) * fontSize; } catch (Exception e) { } return 0.0f; } private static float getDescent(PDFont font, float fontSize) { try { return (font.getFontDescriptor().getDescent() / 1000) * fontSize; } catch (Exception e) { } return 0.0f; } public float getWidth() { return width; } public float getHeight() { return getBottom() - getTop(); } public float getPointSize() { return pointSize; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/MainApp.java
released/MyBox/src/main/java/mara/mybox/MainApp.java
package mara.mybox; import java.util.ResourceBundle; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; import mara.mybox.controller.MyBoxLoadingController; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.sysDefaultLanguage; /** * @Author Mara * @CreateDate 2020-11-7 * @License Apache License Version 2.0 */ public class MainApp extends Application { @Override public void init() throws Exception { } @Override public void start(Stage stage) throws Exception { try { if (AppVariables.MyboxConfigFile == null || !AppVariables.MyboxConfigFile.exists() || !AppVariables.MyboxConfigFile.isFile()) { openStage(stage, Fxmls.MyBoxSetupFxml); } else { MyBoxLoading(stage); } } catch (Exception e) { MyBoxLog.error(e); stage.close(); } } public static void MyBoxLoading(Stage stage) throws Exception { try { FXMLLoader fxmlLoader = openStage(stage, Fxmls.MyBoxLoadingFxml); if (fxmlLoader != null) { MyBoxLoadingController loadController = (MyBoxLoadingController) fxmlLoader.getController(); loadController.run(); } } catch (Exception e) { MyBoxLog.error(e); stage.close(); } } public static FXMLLoader openStage(Stage stage, String fxml) throws Exception { try { String lang = sysDefaultLanguage(); ResourceBundle bundle; if (lang.startsWith("zh")) { bundle = Languages.BundleZhCN; } else { bundle = Languages.BundleEn; } FXMLLoader fxmlLoader = new FXMLLoader(MainApp.class.getResource(fxml), bundle); Pane pane = fxmlLoader.load(); Scene scene = new Scene(pane); stage.setTitle("MyBox v" + AppValues.AppVersion); stage.getIcons().add(AppValues.AppIcon); stage.setScene(scene); stage.show(); return fxmlLoader; } catch (Exception e) { MyBoxLog.error(e); stage.close(); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/MyBox.java
released/MyBox/src/main/java/mara/mybox/MyBox.java
package mara.mybox; import java.io.File; import java.lang.management.ManagementFactory; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import javafx.application.Application; import javafx.application.Platform; import javax.imageio.ImageIO; import mara.mybox.controller.MyBoxLoadingController; import mara.mybox.db.DerbyBase; import mara.mybox.db.migration.DataMigration; import mara.mybox.dev.BaseMacro; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.image.data.ImageColorSpace; import mara.mybox.tools.CertificateTools; import mara.mybox.tools.ConfigTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.MicrosoftDocumentTools; import mara.mybox.tools.SystemTools; import mara.mybox.value.AppPaths; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-1-22 14:35:50 * @License Apache License Version 2.0 */ public class MyBox { public static String InternalRestartFlag = "MyBoxInternalRestarting"; // To pass arguments to JavaFx GUI // https://stackoverflow.com/questions/33549820/javafx-not-calling-mainstring-args-method/33549932#33549932 public static void main(String[] args) { if (args == null) { AppVariables.AppArgs = null; } else { AppVariables.AppArgs = new String[args.length]; System.arraycopy(args, 0, AppVariables.AppArgs, 0, args.length); } initConfigValues(); BaseMacro macro = BaseMacro.create(AppVariables.AppArgs); if (macro != null) { runMacro(macro); } else { launchApp(); } } public static boolean initConfigValues() { MyBoxLog.console("Checking configuration parameters..."); if (AppVariables.AppArgs != null) { for (String arg : AppVariables.AppArgs) { if (arg.startsWith("config=")) { String config = arg.substring("config=".length()); File configFile = new File(config); String dataPath = ConfigTools.readValue(configFile, "MyBoxDataPath"); if (dataPath != null) { try { File dataPathFile = new File(dataPath); if (!dataPathFile.exists()) { dataPathFile.mkdirs(); } else if (!dataPathFile.isDirectory()) { FileDeleteTools.delete(null, dataPathFile); dataPathFile.mkdirs(); } if (dataPathFile.exists() && dataPathFile.isDirectory()) { AppVariables.MyboxConfigFile = configFile; AppVariables.MyboxDataPath = dataPathFile.getAbsolutePath(); return true; } } catch (Exception e) { } } } } } AppVariables.MyboxConfigFile = ConfigTools.defaultConfigFile(); MyBoxLog.console("MyBox Config file:" + AppVariables.MyboxConfigFile); String dataPath = ConfigTools.readValue("MyBoxDataPath"); if (dataPath != null) { try { File dataPathFile = new File(dataPath); if (!dataPathFile.exists()) { dataPathFile.mkdirs(); } else if (!dataPathFile.isDirectory()) { FileDeleteTools.delete(null, dataPathFile); dataPathFile.mkdirs(); } if (dataPathFile.exists() && dataPathFile.isDirectory()) { AppVariables.MyboxDataPath = dataPathFile.getAbsolutePath(); MyBoxLog.console("MyBox Data Path:" + AppVariables.MyboxDataPath); return true; } } catch (Exception e) { } } return true; } public static void runMacro(BaseMacro macro) { if (macro == null) { return; } MyBoxLog.console("Running Mybox Macro..."); MyBoxLog.console("JVM path: " + System.getProperty("java.home")); setSystemProperty(); initEnv(null, Languages.embedLangName()); macro.info(); if (macro.checkParameters()) { macro.run(); macro.displayEnd(); if (macro.isOpenResult()) { File file = macro.getOutputFile(); if (file != null && file.exists()) { AppVariables.AppArgs = new String[1]; AppVariables.AppArgs[0] = file.getAbsolutePath(); launchApp(); return; } } } WindowTools.doExit(); } public static void launchApp() { MyBoxLog.console("Starting Mybox..."); MyBoxLog.console("JVM path: " + System.getProperty("java.home")); if (AppVariables.MyboxDataPath != null && setJVMmemory() && !internalRestart()) { restart(); } else { setSystemProperty(); Application.launch(MainApp.class, AppVariables.AppArgs); } } public static boolean internalRestart() { return AppVariables.AppArgs != null && AppVariables.AppArgs.length > 0 && InternalRestartFlag.equals(AppVariables.AppArgs[0]); } public static boolean setJVMmemory() { String JVMmemory = ConfigTools.readValue("JVMmemory"); if (JVMmemory == null) { return false; } long jvmM = Runtime.getRuntime().maxMemory() / (1024 * 1024); if (JVMmemory.equals("-Xms" + jvmM + "m")) { return false; } if (AppVariables.AppArgs == null || AppVariables.AppArgs.length == 0) { return true; } for (String s : AppVariables.AppArgs) { if (s.startsWith("-Xms")) { return false; } } return true; } // Set properties before JavaFx starting to make sure they take effect against JavaFX public static void setSystemProperty() { try { // https://pdfbox.apache.org/2.0/getting-started.html // System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider"); System.setProperty("org.apache.pdfbox.rendering.UsePureJavaCMYKConversion", "true"); // https://blog.csdn.net/iteye_3493/article/details/82060349 // https://stackoverflow.com/questions/1004327/getting-rid-of-derby-log/1933310#1933310 if (AppVariables.MyboxDataPath != null) { System.setProperty("javax.net.ssl.keyStore", CertificateTools.keystore()); System.setProperty("javax.net.ssl.keyStorePassword", CertificateTools.keystorePassword()); System.setProperty("javax.net.ssl.trustStore", CertificateTools.keystore()); System.setProperty("javax.net.ssl.trustStorePassword", CertificateTools.keystorePassword()); MyBoxLog.console(System.getProperty("javax.net.ssl.keyStore")); } // System.setProperty("derby.language.logQueryPlan", "true"); // System.setProperty("jdk.tls.client.protocols", "TLSv1.1,TLSv1.2"); // System.setProperty("jdk.tls.server.protocols", "TLSv1,TLSv1.1,TLSv1.2,TLSv1.3"); // System.setProperty("https.protocol", "TLSv1"); // System.setProperty("com.sun.security.enableAIAcaIssuers", "true"); // System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); // System.setProperty("javax.net.debug", "ssl,record, plaintext, handshake,session,trustmanager,sslctx"); // System.setProperty("javax.net.debug", "ssl,handshake,session,trustmanager,sslctx"); } catch (Exception e) { MyBoxLog.error(e); } } public static boolean initEnv(MyBoxLoadingController controller, String lang) { try { if (controller != null) { controller.info(MessageFormat.format(message(lang, "InitializeDataUnder"), AppVariables.MyboxDataPath)); } if (!initFiles(controller, lang)) { return false; } if (controller != null) { controller.info(MessageFormat.format(message(lang, "LoadingDatabase"), AppVariables.MyBoxDerbyPath)); } DerbyBase.status = DerbyBase.DerbyStatus.NotConnected; String initDB = DerbyBase.startDerby(); if (!DerbyBase.isStarted()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertWarning(null, initDB); MyBoxLog.console(initDB); }); } AppVariables.initAppVaribles(); } else { // The following statements should be executed in this order if (controller != null) { controller.info(message(lang, "InitializingTables")); } DerbyBase.initTables(null); if (controller != null) { controller.info(message(lang, "InitializingVariables")); } AppVariables.initAppVaribles(); if (controller != null) { controller.info(message(lang, "CheckingMigration")); } MyBoxLog.console(message(lang, "CheckingMigration")); if (!DataMigration.checkUpdates(controller, lang)) { return false; } if (controller != null) { controller.info(message(lang, "InitializingTableValues")); } } try { if (controller != null) { controller.info(message(lang, "InitializingEnv")); } ImageColorSpace.registrySupportedImageFormats(); ImageIO.setUseCache(true); ImageIO.setCacheDirectory(AppVariables.MyBoxTempPath); MicrosoftDocumentTools.registryFactories(); // AlarmClock.scheduleAll(); } catch (Exception e) { if (controller != null) { controller.info(e.toString()); } MyBoxLog.console(e.toString()); } MyBoxLog.info(message(lang, "Load") + " " + AppValues.AppVersion); return true; } catch (Exception e) { if (controller != null) { controller.info(e.toString()); } MyBoxLog.console(e.toString()); return false; } } public static boolean initRootPath(MyBoxLoadingController controller, String lang) { try { File currentDataPath = new File(AppVariables.MyboxDataPath); if (!currentDataPath.exists()) { if (!currentDataPath.mkdirs()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertError(null, MessageFormat.format(message(lang, "UserPathFail"), AppVariables.MyboxDataPath)); }); } return false; } } MyBoxLog.console("MyBox Data Path:" + AppVariables.MyboxDataPath); String oldPath = ConfigTools.readValue("MyBoxOldDataPath"); if (oldPath != null) { if (oldPath.equals(ConfigTools.defaultDataPath())) { FileDeleteTools.deleteDirExcept(null, new File(oldPath), ConfigTools.defaultConfigFile()); } else { FileDeleteTools.deleteDir(new File(oldPath)); } ConfigTools.writeConfigValue("MyBoxOldDataPath", null); } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } public static boolean initFiles(MyBoxLoadingController controller, String lang) { try { if (!initRootPath(controller, lang)) { return false; } AppVariables.MyBoxLogsPath = new File(AppVariables.MyboxDataPath + File.separator + "logs"); if (!AppVariables.MyBoxLogsPath.exists()) { if (!AppVariables.MyBoxLogsPath.mkdirs()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertError(null, MessageFormat.format(message(lang, "UserPathFail"), AppVariables.MyBoxLogsPath)); }); } return false; } } AppVariables.MyBoxDerbyPath = new File(AppVariables.MyboxDataPath + File.separator + "mybox_derby"); System.setProperty("derby.stream.error.file", AppVariables.MyBoxLogsPath + File.separator + "derby.log"); AppVariables.MyBoxLanguagesPath = new File(AppVariables.MyboxDataPath + File.separator + "mybox_languages"); if (!AppVariables.MyBoxLanguagesPath.exists()) { if (!AppVariables.MyBoxLanguagesPath.mkdirs()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertError(null, MessageFormat.format(message(lang, "UserPathFail"), AppVariables.MyBoxLanguagesPath)); }); } return false; } } AppVariables.MyBoxTempPath = new File(AppVariables.MyboxDataPath + File.separator + "AppTemp"); if (!AppVariables.MyBoxTempPath.exists()) { if (!AppVariables.MyBoxTempPath.mkdirs()) { if (controller != null) { Platform.runLater(() -> { PopTools.alertError(null, MessageFormat.format(message(lang, "UserPathFail"), AppVariables.MyBoxTempPath)); }); } return false; } } AppVariables.AlarmClocksFile = AppVariables.MyboxDataPath + File.separator + ".alarmClocks"; AppVariables.MyBoxReservePaths = new ArrayList<File>() { { add(AppVariables.MyBoxTempPath); add(AppVariables.MyBoxDerbyPath); add(AppVariables.MyBoxLanguagesPath); add(new File(AppPaths.getDownloadsPath())); add(AppVariables.MyBoxLogsPath); } }; String prefix = AppPaths.getGeneratedPath() + File.separator; new File(prefix + "png").mkdirs(); new File(prefix + "jpg").mkdirs(); new File(prefix + "pdf").mkdirs(); new File(prefix + "htm").mkdirs(); new File(prefix + "xml").mkdirs(); new File(prefix + "json").mkdirs(); new File(prefix + "txt").mkdirs(); new File(prefix + "csv").mkdirs(); new File(prefix + "md").mkdirs(); new File(prefix + "xlsx").mkdirs(); new File(prefix + "docx").mkdirs(); new File(prefix + "pptx").mkdirs(); new File(prefix + "svg").mkdirs(); new File(prefix + "js").mkdirs(); new File(prefix + "mp4").mkdirs(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } /* restart */ // Restart with parameters. Use "ProcessBuilder", instead of "Runtime.getRuntime().exec" which is not safe // https://stackoverflow.com/questions/4159802/how-can-i-restart-a-java-application?r=SearchResults public static void restart() { try { String javaHome = System.getProperty("java.home"); File boundlesJar; if (SystemTools.isMac()) { boundlesJar = new File(javaHome.substring(0, javaHome.length() - "runtime/Contents/Home".length()) + "Java" + File.separator + "MyBox-" + AppValues.AppVersion + ".jar"); } else { boundlesJar = new File(javaHome.substring(0, javaHome.length() - "runtime".length()) + "app" + File.separator + "MyBox-" + AppValues.AppVersion + ".jar"); } if (boundlesJar.exists()) { restartBundles(boundlesJar); } else { restartJar(); } } catch (Exception e) { MyBoxLog.error(e); } } public static void restartBundles(File jar) { try { MyBoxLog.console("Restarting Mybox bundles..."); List<String> commands = new ArrayList<>(); commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"); String JVMmemory = ConfigTools.readValue("JVMmemory"); if (JVMmemory != null) { commands.add(JVMmemory); } commands.add("-jar"); commands.add(jar.getAbsolutePath()); commands.add(InternalRestartFlag); if (AppVariables.AppArgs != null) { for (String arg : AppVariables.AppArgs) { if (arg != null) { commands.add(arg); } } } ProcessBuilder pb = new ProcessBuilder(commands); pb.start(); System.exit(0); } catch (Exception e) { MyBoxLog.error(e); } } public static void restartJar() { try { MyBoxLog.console("Restarting Mybox Jar package..."); List<String> commands = new ArrayList<>(); commands.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"); List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); for (String jvmArg : jvmArgs) { if (jvmArg != null) { commands.add(jvmArg); } } commands.add("-cp"); commands.add(ManagementFactory.getRuntimeMXBean().getClassPath()); String JVMmemory = ConfigTools.readValue("JVMmemory"); if (JVMmemory != null) { commands.add(JVMmemory); } commands.add(MyBox.class.getName()); commands.add(InternalRestartFlag); if (AppVariables.AppArgs != null) { for (String arg : AppVariables.AppArgs) { if (arg != null) { commands.add(arg); } } } ProcessBuilder pb = new ProcessBuilder(commands); pb.start(); System.exit(0); } catch (Exception e) { MyBoxLog.error(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/Data2DChartGroupSelfComparisonBarsController.java
released/MyBox/src/main/java/mara/mybox/controller/Data2DChartGroupSelfComparisonBarsController.java
package mara.mybox.controller; import javafx.scene.Node; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-10-30 * @License Apache License Version 2.0 */ public class Data2DChartGroupSelfComparisonBarsController extends Data2DChartSelfComparisonBarsController { public Data2DChartGroupSelfComparisonBarsController() { baseTitle = message("GroupData") + " - " + message("SelfComparisonBarsChart"); } @Override public void drawFrame() { if (outputData == null) { return; } outputHtml(makeHtml()); } @Override public Node snapNode() { return webViewController.webView; } /* static */ public static Data2DChartGroupSelfComparisonBarsController open(BaseData2DLoadController tableController) { try { Data2DChartGroupSelfComparisonBarsController controller = (Data2DChartGroupSelfComparisonBarsController) WindowTools.referredStage( tableController, Fxmls.Data2DChartGroupSelfComparisonBarsFxml); controller.setParameters(tableController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/DataTreeQueryResultsController.java
released/MyBox/src/main/java/mara/mybox/controller/DataTreeQueryResultsController.java
package mara.mybox.controller; import java.util.List; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.input.KeyEvent; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.TmpTable; import mara.mybox.db.table.BaseNodeTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2025-5-14 * @License Apache License Version 2.0 */ public class DataTreeQueryResultsController extends BaseData2DLoadController { protected BaseDataTreeController dataController; protected BaseNodeTable nodeTable; protected String info; protected DataTable treeTable; protected TmpTable results; @FXML protected ControlDataTreeNodeView viewController; @Override public void initValues() { try { super.initValues(); leftPaneControl = viewController.leftPaneControl; } catch (Exception e) { MyBoxLog.error(e); } } public void setParameters(BaseController parent, BaseDataTreeController controller, String conditions, TmpTable data) { try { if (parent == null || controller == null || data == null) { close(); return; } parentController = parent; dataController = controller; results = data; nodeTable = dataController.nodeTable; baseName = baseName + "_" + nodeTable.getDataName(); info = conditions; baseTitle = nodeTable.getTreeName() + " - " + message("QueryResults"); setTitle(baseTitle); parentController.setIconified(true); viewController.setParameters(this, nodeTable); loadDef(results); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void postLoadedTableData() { super.postLoadedTableData(); tableView.getColumns().remove(1); } @Override public void clicked(Event event) { List<String> row = selectedItem(); if (row == null) { return; } viewController.loadNode(Long.parseLong(row.get(2))); } @FXML public void dataAction(Event event) { if (results != null) { Data2DManufactureController.openDef(results); } } @FXML public void infoAction(Event event) { if (info != null) { TextPopController.loadText(info); } } @Override public boolean handleKeyEvent(KeyEvent event) { if (super.handleKeyEvent(event)) { return true; } if (viewController != null) { if (viewController.handleKeyEvent(event)) { return true; } } return false; } @Override public boolean needStageVisitHistory() { return false; } @Override public void cleanPane() { try { if (WindowTools.isRunning(parentController)) { parentController.setIconified(false); parentController = null; } dataController = null; } catch (Exception e) { } super.cleanPane(); } /* static */ public static DataTreeQueryResultsController open(BaseController parent, BaseDataTreeController tree, String conditions, TmpTable data) { try { DataTreeQueryResultsController controller = (DataTreeQueryResultsController) WindowTools .forkStage(parent, Fxmls.DataTreeQueryResultsFxml); controller.setParameters(parent, tree, conditions, data); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImagesSpliceController.java
released/MyBox/src/main/java/mara/mybox/controller/ImagesSpliceController.java
package mara.mybox.controller; import java.sql.Connection; import java.util.Arrays; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.VBox; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.WindowTools; import mara.mybox.image.data.ImageCombine; import mara.mybox.image.data.ImageCombine.ArrayType; import mara.mybox.image.data.ImageCombine.CombineSizeType; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.tools.CombineTools; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-8-11 * @License Apache License Version 2.0 */ public class ImagesSpliceController extends BaseController { protected ImageCombine imageCombine; protected int columns, interval, margins, eachWidthValue, eachHeightValue, totalWidthValue, totalHeightValue; @FXML protected ControlImagesTable tableController; @FXML protected ToggleGroup sizeGroup, arrayGroup; @FXML protected RadioButton arrayColumnRadio, arrayRowRadio, arrayColumnsRadio, keepSizeRadio, sizeBiggerRadio, sizeSmallerRadio, eachWidthRadio, eachHeightRadio, totalWidthRadio, totalHeightRadio; @FXML protected TextField totalWidthInput, totalHeightInput, eachWidthInput, eachHeightInput; @FXML protected ComboBox<String> columnsSelector, intervalSelector, marginsSelector; @FXML protected ControlColorSet colorController; @FXML protected ControlImageView viewController; @FXML protected VBox viewBox, sourceBox; public ImagesSpliceController() { baseTitle = Languages.message("ImagesSplice"); } @Override public void initControls() { try { super.initControls(); imageCombine = new ImageCombine(); tableController.parentController = this; tableController.parentFxml = myFxml; initArray(); initSize(); initOthers(); saveButton.disableProperty().bind(viewController.imageView.imageProperty().isNull()); } catch (Exception e) { MyBoxLog.error(e); } } private void initArray() { try { columns = UserConfig.getInt(baseName + "Columns", 2); if (columns <= 0) { columns = 2; } columnsSelector.getItems().addAll(Arrays.asList("2", "3", "4", "5", "6", "7", "8", "9", "10")); columnsSelector.setValue(columns + ""); columnsSelector.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) { checkArray(); } }); String arraySelect = UserConfig.getString(baseName + "ArrayType", "SingleColumn"); switch (arraySelect) { case "SingleColumn": arrayColumnRadio.setSelected(true); break; case "SingleRow": arrayRowRadio.setSelected(true); break; case "ColumnsNumber": arrayColumnsRadio.setSelected(true); break; } arrayGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkArray(); } }); checkArray(); } catch (Exception e) { MyBoxLog.error(e); } } private boolean checkArray() { if (arrayColumnRadio.isSelected() || arrayRowRadio.isSelected()) { columnsSelector.setDisable(true); ValidationTools.setEditorNormal(columnsSelector); return true; } columnsSelector.setDisable(false); int v; try { v = Integer.parseInt(columnsSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0) { columns = v; ValidationTools.setEditorNormal(columnsSelector); return true; } else { ValidationTools.setEditorBadStyle(columnsSelector); popError(message("InvalidParameter") + ": " + message("ColumnsNumber")); return false; } } private void initSize() { try { eachWidthValue = UserConfig.getInt(baseName + "EachWidth", 500); if (eachWidthValue <= 0) { eachWidthValue = 500; } eachWidthInput.setText(eachWidthValue + ""); eachWidthInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkEachWidthValue(); } }); eachHeightValue = UserConfig.getInt(baseName + "EachHeight", 500); if (eachHeightValue <= 0) { eachHeightValue = 500; } eachHeightInput.setText(eachHeightValue + ""); eachHeightInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkEachHeightValue(); } }); totalWidthValue = UserConfig.getInt(baseName + "TotalWidth", 1000); if (totalWidthValue <= 0) { totalWidthValue = 1000; } totalWidthInput.setText(totalWidthValue + ""); totalWidthInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkTotalWidthValue(); } }); totalHeightValue = UserConfig.getInt(baseName + "TotalHeight", 1000); if (totalHeightValue <= 0) { totalHeightValue = 1000; } totalHeightInput.setText(totalHeightValue + ""); totalHeightInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkTotalHeightValue(); } }); String arraySelect = UserConfig.getString(baseName + "SizeType", "KeepSize"); switch (arraySelect) { case "KeepSize": keepSizeRadio.setSelected(true); break; case "AlignAsBigger": sizeBiggerRadio.setSelected(true); break; case "AlignAsSmaller": sizeSmallerRadio.setSelected(true); break; case "EachWidth": eachWidthRadio.setSelected(true); break; case "EachHeight": eachHeightRadio.setSelected(true); break; case "TotalWidth": totalWidthRadio.setSelected(true); break; case "TotalHeight": totalHeightRadio.setSelected(true); break; } sizeGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { checkSize(); } }); checkSize(); } catch (Exception e) { MyBoxLog.error(e); } } private boolean checkSize() { totalWidthInput.setDisable(true); totalWidthInput.setStyle(null); totalHeightInput.setDisable(true); totalHeightInput.setStyle(null); eachWidthInput.setDisable(true); eachWidthInput.setStyle(null); eachHeightInput.setDisable(true); eachHeightInput.setStyle(null); if (keepSizeRadio.isSelected() || sizeBiggerRadio.isSelected() || sizeSmallerRadio.isSelected()) { return true; } else if (eachWidthRadio.isSelected()) { eachWidthInput.setDisable(false); return checkEachWidthValue(); } else if (eachHeightRadio.isSelected()) { eachHeightInput.setDisable(false); return checkEachHeightValue(); } else if (totalWidthRadio.isSelected()) { totalWidthInput.setDisable(false); return checkTotalWidthValue(); } else if (totalHeightRadio.isSelected()) { totalHeightInput.setDisable(false); return checkTotalHeightValue(); } return false; } private boolean checkEachWidthValue() { int v; try { v = Integer.parseInt(eachWidthInput.getText()); } catch (Exception e) { v = -1; } if (v > 0) { eachWidthValue = v; eachWidthInput.setStyle(null); return true; } else { eachWidthInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("EachWidth")); return false; } } private boolean checkEachHeightValue() { int v; try { v = Integer.parseInt(eachHeightInput.getText()); } catch (Exception e) { v = -1; } if (v > 0) { eachHeightValue = v; eachHeightInput.setStyle(null); return true; } else { eachHeightInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("EachHeight")); return false; } } private boolean checkTotalWidthValue() { int v; try { v = Integer.parseInt(totalWidthInput.getText()); } catch (Exception e) { v = -1; } if (v > 0) { totalWidthValue = v; totalWidthInput.setStyle(null); return true; } else { totalWidthInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("TotalWidth")); return false; } } private boolean checkTotalHeightValue() { int v; try { v = Integer.parseInt(totalHeightInput.getText()); } catch (Exception e) { v = -1; } if (v > 0) { totalHeightValue = v; totalHeightInput.setStyle(null); return true; } else { totalHeightInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("TotalHeight")); return false; } } private void initOthers() { try { interval = UserConfig.getInt(baseName + "Interval", 0); intervalSelector.getItems().addAll( Arrays.asList("0", "5", "-5", "1", "-1", "10", "-10", "15", "-15", "20", "-20", "30", "-30")); intervalSelector.setValue(interval + ""); intervalSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkInterval(); } }); margins = UserConfig.getInt(baseName + "Margins", 0); marginsSelector.getItems().addAll(Arrays.asList("0", "5", "-5", "10", "-10", "20", "-20", "30", "-30")); marginsSelector.setValue(margins + ""); marginsSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> v, String ov, String nv) { checkMargins(); } }); colorController.init(this, baseName + "Color"); } catch (Exception e) { MyBoxLog.error(e); } } private boolean checkInterval() { try { interval = Integer.parseInt(intervalSelector.getValue()); ValidationTools.setEditorNormal(intervalSelector); return true; } catch (Exception e) { ValidationTools.setEditorBadStyle(intervalSelector); popError(message("InvalidParameter") + ": " + message("Interval")); return false; } } private boolean checkMargins() { try { margins = Integer.parseInt(marginsSelector.getValue()); ValidationTools.setEditorNormal(marginsSelector); return true; } catch (Exception e) { ValidationTools.setEditorBadStyle(marginsSelector); popError(message("InvalidParameter") + ": " + message("Margins")); return false; } } public boolean checkOptions() { if (tableController.tableData == null || tableController.tableData.isEmpty() || !checkArray() || !checkSize() || !checkInterval() || !checkMargins()) { return false; } try (Connection conn = DerbyBase.getConnection()) { if (arrayColumnRadio.isSelected()) { imageCombine.setArrayType(ArrayType.SingleColumn); UserConfig.setString(conn, baseName + "ArrayType", "SingleColumn"); } else if (arrayRowRadio.isSelected()) { imageCombine.setArrayType(ArrayType.SingleRow); UserConfig.setString(conn, baseName + "ArrayType", "SingleRow"); } else if (arrayColumnsRadio.isSelected()) { imageCombine.setArrayType(ArrayType.ColumnsNumber); imageCombine.setColumnsValue(columns); UserConfig.setString(conn, baseName + "ArrayType", "ColumnsNumber"); UserConfig.setInt(conn, baseName + "Columns", columns); } if (keepSizeRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.KeepSize); UserConfig.setString(conn, baseName + "SizeType", "KeepSize"); } else if (sizeBiggerRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.AlignAsBigger); UserConfig.setString(conn, baseName + "SizeType", "AlignAsBigger"); } else if (sizeSmallerRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.AlignAsSmaller); UserConfig.setString(conn, baseName + "SizeType", "AlignAsSmaller"); } else if (eachWidthRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.EachWidth); imageCombine.setEachWidthValue(eachWidthValue); UserConfig.setString(conn, baseName + "SizeType", "EachWidth"); UserConfig.setInt(conn, baseName + "EachWidth", eachWidthValue); } else if (eachHeightRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.EachHeight); imageCombine.setEachHeightValue(eachHeightValue); UserConfig.setString(conn, baseName + "SizeType", "EachHeight"); UserConfig.setInt(conn, baseName + "EachHeight", eachHeightValue); } else if (totalWidthRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.TotalWidth); imageCombine.setTotalWidthValue(totalWidthValue); UserConfig.setString(conn, baseName + "SizeType", "TotalWidth"); UserConfig.setInt(conn, baseName + "TotalWidth", totalWidthValue); } else if (totalHeightRadio.isSelected()) { imageCombine.setSizeType(CombineSizeType.TotalHeight); imageCombine.setTotalHeightValue(totalHeightValue); UserConfig.setString(conn, baseName + "SizeType", "TotalHeight"); UserConfig.setInt(conn, baseName + "TotalHeight", totalHeightValue); } imageCombine.setIntervalValue(interval); UserConfig.setInt(conn, baseName + "Interval", interval); imageCombine.setMarginsValue(margins); UserConfig.setInt(conn, baseName + "Margins", margins); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @FXML @Override public void goAction() { if (!checkOptions()) { return; } List<ImageInformation> imageInfos = tableController.selectedItems(); if (imageInfos == null || imageInfos.isEmpty()) { imageInfos = tableController.tableData; } if (imageInfos == null || imageInfos.isEmpty()) { popError(message("SelectToHandle")); return; } List<ImageInformation> infos = imageInfos; imageCombine.setBgColor(colorController.color()); if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { Image image; @Override protected boolean handle() { if (imageCombine.getArrayType() == ArrayType.SingleColumn) { image = CombineTools.combineSingleColumn(this, imageCombine, infos, false, true); } else if (imageCombine.getArrayType() == ArrayType.SingleRow) { image = CombineTools.combineSingleRow(this, imageCombine, infos, false, true); } else if (imageCombine.getArrayType() == ArrayType.ColumnsNumber) { image = CombineTools.combineImagesColumns(this, imageCombine, infos); } else { image = null; } return image != null; } @Override protected void whenSucceeded() { viewController.image = image; viewController.imageView.setImage(image); viewController.setZoomStep(image); viewController.fitSize(); viewController.imageLabel.setText(Languages.message("CombinedSize") + ": " + (int) image.getWidth() + "x" + (int) image.getHeight()); } }; start(task); } @FXML @Override public void saveAction() { viewController.saveAsAction(); } @FXML @Override public boolean menuAction(Event event) { if (viewBox.isFocused() || viewBox.isFocusWithin()) { viewController.menuAction(event); return true; } else if (sourceBox.isFocused() || sourceBox.isFocusWithin()) { tableController.menuAction(event); return true; } return super.menuAction(event); } @FXML @Override public boolean popAction() { if (viewBox.isFocused() || viewBox.isFocusWithin()) { viewController.popAction(); return true; } else if (sourceBox.isFocused() || sourceBox.isFocusWithin()) { tableController.popAction(); return true; } return super.popAction(); } @Override public boolean handleKeyEvent(KeyEvent event) { if (viewBox.isFocused() || viewBox.isFocusWithin()) { if (viewController.handleKeyEvent(event)) { return true; } } else if (sourceBox.isFocused() || sourceBox.isFocusWithin()) { if (tableController.handleKeyEvent(event)) { return true; } } if (super.handleKeyEvent(event)) { return true; } if (viewController.handleKeyEvent(event)) { return true; } return tableController.handleKeyEvent(event); } /* static methods */ public static ImagesSpliceController open(List<ImageInformation> imageInfos) { try { ImagesSpliceController controller = (ImagesSpliceController) WindowTools.openStage(Fxmls.ImagesSpliceFxml); controller.tableController.tableData.setAll(imageInfos);; return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/LoadingController.java
released/MyBox/src/main/java/mara/mybox/controller/LoadingController.java
package mara.mybox.controller; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import javafx.application.Platform; import javafx.beans.property.SimpleBooleanProperty; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.ProgressIndicator; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.DateTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-6-11 8:14:06 * @License Apache License Version 2.0 */ public class LoadingController extends BaseLogsController { private Task<?> loadingTask; protected SimpleBooleanProperty canceled; @FXML protected ProgressIndicator progressIndicator; @FXML protected Label timeLabel; public LoadingController() { canceled = new SimpleBooleanProperty(); } public void init(final Task<?> task) { try { loadingTask = task; canceled.set(false); progressIndicator.setProgress(-1F); if (timeLabel != null) { showTimer(); } getMyStage().toFront(); if (task != null && (task instanceof FxTask)) { FxTask stask = (FxTask) task; setTitle(stask.getController().getTitle()); setInfo(getTitle()); } else { setInfo(message("Handling...")); } logsTextArea.requestFocus(); } catch (Exception e) { MyBoxLog.error(e); } } public void showTimer() { try { if (timer != null) { timer.cancel(); } final Date startTime = new Date(); final String prefix = message("StartTime") + ": " + DateTools.nowString() + " " + message("ElapsedTime") + ": "; timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { Platform.runLater(() -> { if (loadingTask != null && loadingTask.isCancelled()) { cancelAction(); return; } timeLabel.setText(prefix + DateTools.datetimeMsDuration(new Date(), startTime)); }); Platform.requestNextPulse(); } }, 0, 1000); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void cancelAction() { clear(); closeStage(); } public void clear() { canceled.set(true); if (loadingTask != null) { if (parentController != null) { parentController.taskCanceled(loadingTask); } loadingTask.cancel(); loadingTask = null; } if (timer != null) { timer.cancel(); timer = null; } } public void setInfo(String info) { updateLogs(info, true); } public String getInfo() { return logsTextArea.getText(); } @Override public boolean isRunning() { return timer != null; } public boolean canceled() { return canceled != null && canceled.get(); } public void setProgress(float value) { if (loadingTask == null || loadingTask.isDone()) { return; } progressIndicator.setProgress(value); } public ProgressIndicator getProgressIndicator() { return progressIndicator; } public void setProgressIndicator(ProgressIndicator progressIndicator) { this.progressIndicator = progressIndicator; } public Task<?> getLoadingTask() { return loadingTask; } public void setLoadingTask(Task<?> loadingTask) { this.loadingTask = loadingTask; } public Label getTimeLabel() { return timeLabel; } public void setTimeLabel(Label timeLabel) { this.timeLabel = timeLabel; } @Override public void cleanPane() { try { clear(); } catch (Exception e) { } super.cleanPane(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlStroke.java
released/MyBox/src/main/java/mara/mybox/controller/ControlStroke.java
package mara.mybox.controller; import java.awt.BasicStroke; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.image.ImageView; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.shape.StrokeLineCap; import javafx.scene.shape.StrokeLineJoin; import mara.mybox.data.ShapeStyle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-8-13 * @License Apache License Version 2.0 */ public class ControlStroke extends BaseController { protected BaseShapeController shapeController; protected ShapeStyle style; @FXML protected ControlColorSet colorController, fillController; @FXML protected ComboBox<String> widthSelector, limitSelector, fillOpacitySelector; @FXML protected ToggleGroup joinGroup, capGroup; @FXML protected RadioButton joinMiterRadio, joinBevelRadio, joinRoundRadio, capButtRadio, capSquareRadio, capRoundRadio; @FXML protected TextField arrayInput, offsetInput; @FXML protected CheckBox dashCheck, fillCheck; @FXML protected VBox fillBox; @FXML protected FlowPane fillOpacityPane; protected void setParameters(BaseShapeController parent) { try { if (parent == null) { return; } shapeController = parent; baseName = parent.baseName; style = new ShapeStyle(baseName); colorController.init(this, baseName + "Color", style.getStrokeColor()); widthSelector.setValue((int) style.getStrokeWidth() + ""); switch (style.getStrokeLineJoinAwt()) { case BasicStroke.JOIN_ROUND: joinRoundRadio.setSelected(true); break; case BasicStroke.JOIN_BEVEL: joinBevelRadio.setSelected(true); break; default: joinMiterRadio.setSelected(true); break; } List<String> vl = new ArrayList<>(); vl.addAll(Arrays.asList("10", "5", "2", "1", "8", "15", "20")); int iv = (int) style.getStrokeLineLimit(); if (!vl.contains(iv + "")) { vl.add(0, iv + ""); } limitSelector.getItems().setAll(vl); limitSelector.setValue(iv + ""); switch (style.getStrokeLineCapAwt()) { case BasicStroke.CAP_ROUND: capRoundRadio.setSelected(true); break; case BasicStroke.CAP_SQUARE: capSquareRadio.setSelected(true); break; default: capButtRadio.setSelected(true); break; } dashCheck.setSelected(style.isIsStrokeDash()); if (arrayInput != null) { arrayInput.setText(style.getStrokeDashText()); } if (offsetInput != null) { offsetInput.setText(style.getDashOffset() + ""); } fillCheck.setSelected(style.isIsFillColor()); fillController.init(this, baseName + "Fill", style.getFillColor()); vl = new ArrayList<>(); vl.addAll(Arrays.asList("0.5", "0.3", "0", "1.0", "0.05", "0.02", "0.1", "0.2", "0.8", "0.6", "0.4", "0.7", "0.9")); float fv = style.getFillOpacity(); if (!vl.contains(fv + "")) { vl.add(0, fv + ""); } fillOpacitySelector.getItems().setAll(vl); fillOpacitySelector.setValue(fv + ""); if (shapeController instanceof BaseImageEditController) { fillBox.getChildren().remove(fillOpacityPane); } } catch (Exception e) { MyBoxLog.error(e); } } protected void setWidthList() { isSettingValues = true; setWidthList(widthSelector, shapeController.imageView, (int) style.getStrokeWidth()); isSettingValues = false; } protected static void setWidthList(ComboBox<String> selector, ImageView view, int initValue) { if (selector == null || view == null) { return; } List<String> ws = new ArrayList<>(); ws.addAll(Arrays.asList("2", "3", "1", "5", "8", "10", "15", "25", "30", "50", "80", "100", "150", "200", "300", "500")); int max = (int) view.getImage().getWidth(); int step = max / 10; for (int w = 10; w < max; w += step) { if (!ws.contains(w + "")) { ws.add(0, w + ""); } } if (initValue >= 0) { if (!ws.contains(initValue + "")) { ws.add(0, initValue + ""); } } else { initValue = 2; } selector.getItems().setAll(ws); selector.setValue(initValue + ""); } protected ShapeStyle pickValues() { float v = -1; try { v = Float.parseFloat(widthSelector.getValue()); } catch (Exception e) { } if (v <= 0) { popError(message("InvalidParameter") + ": " + message("Width")); return null; } style.setStrokeWidth(v); style.setStrokeColor(colorController.color()); if (joinRoundRadio.isSelected()) { style.setStrokeLineJoin(StrokeLineJoin.ROUND); } else if (joinBevelRadio.isSelected()) { style.setStrokeLineJoin(StrokeLineJoin.BEVEL); } else { style.setStrokeLineJoin(StrokeLineJoin.MITER); } v = -1; try { v = Float.parseFloat(limitSelector.getValue()); } catch (Exception e) { } if (v < 1) { popError(message("InvalidParameter") + ": " + message("StrokeMiterLimit")); return null; } style.setStrokeLineLimit(v); if (capRoundRadio.isSelected()) { style.setStrokeLineCap(StrokeLineCap.ROUND); } else if (capSquareRadio.isSelected()) { style.setStrokeLineCap(StrokeLineCap.SQUARE); } else { style.setStrokeLineCap(StrokeLineCap.BUTT); } style.setIsStrokeDash(dashCheck.isSelected()); if (dashCheck.isSelected()) { List<Double> values = ShapeStyle.text2StrokeDash(arrayInput.getText()); if (values == null || values.isEmpty()) { popError(message("InvalidParameter") + ": " + message("StrokeDashArray")); return null; } style.setStrokeDash(values); v = -1; try { v = Float.parseFloat(offsetInput.getText()); } catch (Exception e) { } if (v < 0) { popError(message("InvalidParameter") + ": " + message("StrokeDashOffset")); return null; } style.setDashOffset(v); } style.setIsFillColor(fillCheck.isSelected()); style.setFillColor(fillController.color()); if (fillCheck.isSelected()) { v = -1; try { v = Float.parseFloat(fillOpacitySelector.getValue()); } catch (Exception e) { } if (v < 0 || v > 1) { popError(message("InvalidParameter") + ": " + message("FillOpacity")); return null; } style.setFillOpacity(v); } style.save(); return style; } @FXML public void aboutStroke() { openLink(HelpTools.strokeLink()); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/HtmlDomDeleteController.java
released/MyBox/src/main/java/mara/mybox/controller/HtmlDomDeleteController.java
package mara.mybox.controller; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableView; import mara.mybox.data.HtmlNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import org.jsoup.nodes.Element; /** * @Author Mara * @CreateDate 2023-3-6 * @License Apache License Version 2.0 */ public class HtmlDomDeleteController extends BaseChildController { protected BaseHtmlFormat editor; protected TreeTableView<HtmlNode> sourceTree; protected BaseHtmlTreeController manageController; protected int count; @FXML protected ControlHtmlDomSource sourceController; public HtmlDomDeleteController() { baseTitle = message("DeleteNodes"); } public void setParamters(BaseHtmlFormat editor, TreeItem<HtmlNode> sourceItem) { try { this.editor = editor; if (invalidTarget()) { return; } manageController = editor.domController; Element root = manageController.treeView.getRoot().getValue().getElement(); sourceController.load(root, sourceItem); sourceController.setLabel(message("Select")); sourceTree = sourceController.treeView; } catch (Exception e) { MyBoxLog.error(e); closeStage(); } } public boolean invalidTarget() { if (editor == null || editor.getMyStage() == null || !editor.getMyStage().isShowing()) { popError(message("Invalid")); closeStage(); return true; } return false; } public boolean checkParameters() { return !invalidTarget(); } @FXML @Override public void okAction() { if (!checkParameters()) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { return delete(); } @Override protected void whenSucceeded() { if (count > 0) { closeStage(); manageController.refreshAction(); editor.domChanged(true); } editor.popInformation(message("Deleted") + ": " + count); } }; start(task); } protected boolean delete() { try { count = 0; List<TreeItem<HtmlNode>> sourcesItems = sourceController.selectedItems(); for (TreeItem<HtmlNode> sourceItem : sourcesItems) { String sourceNumber = sourceController.makeHierarchyNumber(sourceItem); TreeItem<HtmlNode> manageItem = manageController.findSequenceNumber(sourceNumber); Element selectedElement = manageItem.getValue().getElement(); selectedElement.remove(); count++; } return true; } catch (Exception e) { error = e.toString(); return false; } } /* static methods */ public static HtmlDomDeleteController open(BaseHtmlFormat editor, TreeItem<HtmlNode> sourceItem) { if (editor == null) { return null; } HtmlDomDeleteController controller = (HtmlDomDeleteController) WindowTools.childStage( editor, Fxmls.HtmlDomDeleteFxml); if (controller != null) { controller.setParamters(editor, sourceItem); controller.requestMouse(); } return controller; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/Data2DGroupStatisticController.java
released/MyBox/src/main/java/mara/mybox/controller/Data2DGroupStatisticController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.CheckBox; import javafx.scene.control.RadioButton; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.layout.FlowPane; import mara.mybox.calculation.DescriptiveStatistic; import mara.mybox.calculation.DescriptiveStatistic.StatisticObject; import mara.mybox.calculation.DescriptiveStatistic.StatisticType; import mara.mybox.data2d.DataFileCSV; import mara.mybox.data2d.DataTableGroup; import mara.mybox.data2d.DataTableGroupStatistic; import mara.mybox.db.data.ColumnDefinition; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxBackgroundTask; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.chart.PieChartMaker; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.DoubleTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-8-10 * @License Apache License Version 2.0 */ public class Data2DGroupStatisticController extends Data2DChartXYController { protected DescriptiveStatistic calculation; protected DataFileCSV dataFile; protected PieChartMaker pieMaker; protected List<List<String>> pieData; protected List<Data2DColumn> pieColumns; protected int pieMaxData; @FXML protected TabPane chartTabPane; @FXML protected Tab groupDataTab, statisticDataTab, chartDataTab, xyChartTab, pieChartTab; @FXML protected ControlStatisticSelection statisticController; @FXML protected ControlData2DView statisticDataController, chartDataController; @FXML protected ControlData2DChartPie pieChartController; @FXML protected FlowPane columnsDisplayPane, valuesDisplayPane; @FXML protected RadioButton xyParametersRadio, pieParametersRadio; @FXML protected ToggleGroup pieCategoryGroup; @FXML protected TextField pieMaxInput; public Data2DGroupStatisticController() { baseTitle = message("GroupStatistic"); } @Override public void initOptions() { try { super.initOptions(); pieMaker = pieChartController.pieMaker; pieChartController.redrawNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { drawPieChart(); } }); pieMaxData = UserConfig.getInt(baseName + "PieMaxData", 100); if (pieMaxData <= 0) { pieMaxData = 100; } if (pieMaxInput != null) { pieMaxInput.setText(pieMaxData + ""); } statisticController.mustCount(); chartDataController.loadedNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { xyChartTab.setDisable(false); pieChartTab.setDisable(false); refreshAction(); } }); pieCategoryGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue ov, Toggle oldValue, Toggle newValue) { makeCharts(false, true); } }); xyChartTab.setDisable(true); pieChartTab.setDisable(true); displayAllCheck.visibleProperty().unbind(); displayAllCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { refreshAction(); } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(displayAllCheck, new Tooltip(message("AllRowsLoadComments"))); } catch (Exception e) { MyBoxLog.debug(e); } } @Override public boolean checkOptions() { if (!groupController.pickValues()) { return false; } checkObject(); checkInvalidAs(); return true; } @Override public boolean initChart() { return initChart(false); } @Override protected void startOperation() { if (task != null) { task.cancel(); } dataFile = null; groupDataController.loadNull(); statisticDataController.loadNull(); chartDataController.loadNull(); xyChartTab.setDisable(true); pieChartTab.setDisable(true); calculation = statisticController.pickValues() .setStatisticObject(StatisticObject.Columns) .setScale(scale) .setInvalidAs(invalidAs) .setTaskController(this) .setData2D(data2D) .setColsIndices(checkedColsIndices) .setColsNames(checkedColsNames); columnsDisplayPane.getChildren().clear(); for (String c : checkedColsNames) { columnsDisplayPane.getChildren().add(new CheckBox(c)); } valuesDisplayPane.getChildren().clear(); for (StatisticType t : calculation.types) { valuesDisplayPane.getChildren().add(new CheckBox(message(t.name()))); } taskSuccessed = false; task = new FxSingletonTask<Void>(this) { private DataTableGroup group; private DataTableGroupStatistic statistic; @Override protected boolean handle() { try { data2D.setTask(this); group = groupData(DataTableGroup.TargetType.Table, checkedColsIndices, false, -1, scale); if (!group.run()) { return false; } if (task == null || isCancelled()) { return false; } task.setInfo(message("Statistic") + "..."); statistic = new DataTableGroupStatistic() .setGroups(group).setCountChart(true) .setCalculation(calculation) .setCalNames(checkedColsNames) .setTask(this); if (!statistic.run()) { return false; } if (task == null || isCancelled()) { return false; } dataFile = statistic.getChartData(); taskSuccessed = dataFile != null; return taskSuccessed; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { chartDataController.loadDef(dataFile); groupDataController.loadDef(group.getTargetData()); statisticDataController.loadDef(statistic.getStatisticData()); rightPane.setDisable(false); } @Override protected void finalAction() { super.finalAction(); closeTask(ok); } }; start(task, false); } @FXML public void makeCharts(boolean forXY, boolean forPie) { if (forXY) { outputColumns = null; outputData = null; chartMaker.clearChart(); } if (forPie) { pieColumns = null; pieData = null; pieMaker.clearChart(); } if (dataFile == null) { return; } if (backgroundTask != null) { backgroundTask.cancel(); backgroundTask = null; } backgroundTask = new FxBackgroundTask<Void>(this) { @Override protected boolean handle() { try { dataFile.startTask(this, null); List<List<String>> resultsData; if (displayAllCheck.isSelected()) { resultsData = dataFile.allRows(false); } else { resultsData = chartDataController.data2D.pageData(); } if (resultsData == null) { return false; } if (forXY && !makeXYData(resultsData)) { return false; } if (forPie && !makePieData(resultsData)) { return false; } return true; } catch (Exception e) { error = e.toString(); MyBoxLog.error(e); return false; } } @Override protected void whenSucceeded() { if (forXY) { drawXYChart(); } if (forPie) { drawPieChart(); } } @Override protected void whenFailed() { } @Override protected void finalAction() { super.finalAction(); dataFile.stopTask(); } }; start(backgroundTask, false); } protected boolean makeXYData(List<List<String>> resultsData) { try { if (resultsData == null) { return false; } outputColumns = new ArrayList<>(); Data2DColumn xyCategoryColumn = dataFile.column(xyParametersRadio.isSelected() ? 1 : 0); outputColumns.add(xyCategoryColumn); List<String> colNames = new ArrayList<>(); List<String> allName = new ArrayList<>(); for (Node n : columnsDisplayPane.getChildren()) { CheckBox cb = (CheckBox) n; String name = Data2DColumn.getCheckBoxColumnName(cb); if (cb.isSelected()) { colNames.add(name); } allName.add(name); } if (colNames.isEmpty()) { if (allName.isEmpty()) { error = message("SelectToHanlde") + ": " + message("ColumnsDisplayed"); return false; } colNames = allName; } List<String> sTypes = new ArrayList<>(); List<String> allTypes = new ArrayList<>(); for (Node n : valuesDisplayPane.getChildren()) { CheckBox cb = (CheckBox) n; String tname = Data2DColumn.getCheckBoxColumnName(cb); if (cb.isSelected()) { sTypes.add(tname); } allTypes.add(tname); } if (sTypes.isEmpty()) { if (allTypes.isEmpty()) { error = message("SelectToHanlde") + ": " + message("ValuesDisplayed"); return false; } sTypes = allTypes; } List<Integer> cols = new ArrayList<>(); for (String stype : sTypes) { if (message("Count").equals(stype)) { outputColumns.add(dataFile.column(2)); cols.add(2); } else { for (String col : colNames) { int colIndex = dataFile.colOrder(col + "_" + stype); outputColumns.add(dataFile.column(colIndex)); cols.add(colIndex); } } } outputData = new ArrayList<>(); for (List<String> data : resultsData) { List<String> xyRow = new ArrayList<>(); String category = data.get(xyParametersRadio.isSelected() ? 1 : 0); xyRow.add(category); for (int colIndex : cols) { xyRow.add(data.get(colIndex)); } outputData.add(xyRow); } selectedCategory = xyCategoryColumn.getColumnName(); selectedValue = message("Statistic"); return initChart(); } catch (Exception e) { error = e.toString(); MyBoxLog.error(e); return false; } } protected boolean makePieData(List<List<String>> resultsData) { try { if (resultsData == null) { return false; } pieColumns = new ArrayList<>(); Data2DColumn pieCategoryColumn = dataFile.columns.get(pieParametersRadio.isSelected() ? 1 : 0); pieColumns.add(pieCategoryColumn); pieColumns.add(dataFile.columns.get(2)); pieColumns.add(new Data2DColumn(message("Percentage"), ColumnDefinition.ColumnType.Double)); pieData = new ArrayList<>(); double sum = 0, count; for (List<String> data : resultsData) { try { sum += Double.parseDouble(data.get(2)); } catch (Exception e) { } } for (List<String> data : resultsData) { try { String category = data.get(pieParametersRadio.isSelected() ? 1 : 0); List<String> pieRow = new ArrayList<>(); pieRow.add(category); count = Double.parseDouble(data.get(2)); pieRow.add((long) count + ""); pieRow.add(DoubleTools.percentage(count, sum, scale)); pieData.add(pieRow); } catch (Exception e) { } } selectedCategory = pieCategoryColumn.getColumnName(); String title = chartTitle(); pieMaker.init(message("PieChart")) .setDefaultChartTitle(title + " - " + message("Count")) .setDefaultCategoryLabel(selectedCategory) .setDefaultValueLabel(message("Count")) .setValueLabel(message("Count")) .setInvalidAs(invalidAs); return true; } catch (Exception e) { error = e.toString(); MyBoxLog.error(e); return false; } } @Override public void drawChart() { drawXYChart(); drawPieChart(); } @Override public void drawXYChart() { try { chartData = chartMax(); if (chartData == null || chartData.isEmpty()) { return; } chartController.writeXYChart(outputColumns, chartData); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void drawPieChart() { try { if (pieData == null || pieData.isEmpty()) { popError(message("NoData")); return; } List<List<String>> maxPieData; if (pieMaxData > 0 && pieMaxData < pieData.size()) { maxPieData = pieData.subList(0, pieMaxData); } else { maxPieData = pieData; } pieChartController.writeChart(pieColumns, maxPieData); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void goXYchart() { makeCharts(true, false); } @FXML @Override public void refreshAction() { makeCharts(true, true); } @Override public void typeChanged() { initChart(); goXYchart(); } @FXML public void pieMaxAction() { if (pieMaxInput != null) { boolean ok; String s = pieMaxInput.getText(); if (s == null || s.isBlank()) { pieMaxData = -1; ok = true; } else { try { int v = Integer.parseInt(s); if (v > 0) { pieMaxData = v; ok = true; } else { ok = false; } } catch (Exception ex) { ok = false; } } if (ok) { UserConfig.setInt(baseName + "PieMaxData", pieMaxData); pieMaxInput.setStyle(null); } else { pieMaxInput.setStyle(UserConfig.badStyle()); popError(message("Invalid") + ": " + message("Maximum")); return; } } drawPieChart(); } @FXML @Override public boolean menuAction(Event event) { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == groupDataTab) { return groupDataController.menuAction(event); } else if (tab == statisticDataTab) { return statisticDataController.menuAction(event); } else if (tab == chartDataTab) { return chartDataController.menuAction(event); } else if (tab == xyChartTab) { return chartController.menuAction(event); } else if (tab == pieChartTab) { return pieChartController.menuAction(event); } return false; } @FXML @Override public boolean popAction() { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == groupDataTab) { return groupDataController.popAction(); } else if (tab == statisticDataTab) { return statisticDataController.popAction(); } else if (tab == chartDataTab) { return chartDataController.popAction(); } else if (tab == xyChartTab) { return chartController.popAction(); } else if (tab == pieChartTab) { return pieChartController.popAction(); } return false; } @Override public boolean controlAlt2() { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == xyChartTab) { return chartController.controlAlt2(); } else if (tab == pieChartTab) { return pieChartController.controlAlt2(); } return false; } @Override public boolean controlAlt3() { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == xyChartTab) { return chartController.controlAlt3(); } else if (tab == pieChartTab) { return pieChartController.controlAlt3(); } return false; } @Override public boolean controlAlt4() { Tab tab = chartTabPane.getSelectionModel().getSelectedItem(); if (tab == xyChartTab) { return chartController.controlAlt4(); } else if (tab == pieChartTab) { return pieChartController.controlAlt4(); } return false; } /* static */ public static Data2DGroupStatisticController open(BaseData2DLoadController tableController) { try { Data2DGroupStatisticController controller = (Data2DGroupStatisticController) WindowTools.referredStage( tableController, Fxmls.Data2DGroupStatisticFxml); controller.setParameters(tableController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/SvgFromImageController.java
released/MyBox/src/main/java/mara/mybox/controller/SvgFromImageController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import java.io.File; import java.nio.charset.Charset; import javafx.embed.swing.SwingFXUtils; import javafx.fxml.FXML; import javafx.scene.image.Image; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.FileTmpTools; import mara.mybox.tools.SvgTools; import mara.mybox.tools.TextFileTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-6-29 * @License Apache License Version 2.0 */ public class SvgFromImageController extends BaseChildController { protected BufferedImage bufferedImage; @FXML protected ControlSvgFromImage optionsController; public SvgFromImageController() { baseTitle = message("ImageToSvg"); } public void setParameters(Image image) { if (image == null) { close(); return; } bufferedImage = SwingFXUtils.fromFXImage(image, null); } @FXML @Override public void startAction() { if (!optionsController.pickValues()) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private File svgFile; @Override protected boolean handle() { try { String svg = SvgTools.imageToSvg(this, myController, bufferedImage, optionsController); if (svg == null || svg.isBlank() || !isWorking()) { return false; } svgFile = FileTmpTools.generateFile(optionsController.getQuantization().name(), "svg"); svgFile = TextFileTools.writeFile(svgFile, svg, Charset.forName("utf-8")); return svgFile != null && svgFile.exists(); } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { SvgEditorController.open(svgFile); if (closeAfterCheck.isSelected()) { close(); } } }; start(task); } /* static methods */ public static SvgFromImageController open(Image image) { SvgFromImageController controller = (SvgFromImageController) WindowTools.openStage(Fxmls.SvgFromImageFxml); if (controller != null) { controller.setParameters(image); controller.requestMouse(); } return controller; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ColorQueryController.java
released/MyBox/src/main/java/mara/mybox/controller/ColorQueryController.java
package mara.mybox.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.RadioButton; import javafx.scene.control.Tab; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import mara.mybox.db.data.ColorData; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.style.HtmlStyles; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-8-29 * @License Apache License Version 2.0 */ public class ColorQueryController extends BaseController { protected ColorData colorData; @FXML protected Tab colorTab, resultTab; @FXML protected ControlColorInput colorController; @FXML protected Button refreshButton, paletteButton; @FXML protected TextField separatorInput; @FXML protected ToggleGroup separatorGroup; @FXML protected RadioButton commaRadio, hyphenRadio, colonRadio, blankRadio, inputRadio; @FXML protected HtmlTableController htmlController; public ColorQueryController() { baseTitle = message("QueryColor"); } @Override public void initControls() { try { separatorGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { if (!inputRadio.isSelected()) { goAction(); } } }); separatorInput.setText(UserConfig.getString(baseName + "Separator", null)); goButton.disableProperty().bind(colorController.colorInput.textProperty().isEmpty() .or(separatorInput.textProperty().isEmpty()) ); htmlController.initStyle(HtmlStyles.TableStyle); initMore(); } catch (Exception e) { MyBoxLog.error(e); } } public void initMore() { try { colorController.setParameter(baseName, Color.GOLD); colorController.updateNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { goAction(); } }); goAction(); } catch (Exception e) { MyBoxLog.error(e); } } public String pickSeparator() { try { String separator = ", "; if (commaRadio.isSelected()) { separator = ", "; } else if (hyphenRadio.isSelected()) { separator = "-"; } else if (colonRadio.isSelected()) { separator = ":"; } else if (blankRadio.isSelected()) { separator = " "; } else if (inputRadio.isSelected()) { separator = separatorInput.getText(); if (separator == null || separator.isEmpty()) { return null; } UserConfig.setString(baseName + "Separator", separator); } return separator; } catch (Exception e) { MyBoxLog.error(e); return null; } } @FXML @Override public void goAction() { try { colorData = colorController.colorData; if (colorData == null || colorData.getRgba() == null) { return; } String separator = pickSeparator(); if (separator == null || separator.isEmpty()) { popError(message("InvalidParamter") + ": " + message("ValueSeparator")); return; } colorData = new ColorData(colorData.getRgba()) .setvSeparator(separator).convert(); htmlController.displayHtml(colorData.html()); } catch (Exception e) { MyBoxLog.error(e); } } @FXML protected void popHelps(Event event) { if (UserConfig.getBoolean("ColorHelpsPopWhenMouseHovering", false)) { showHelps(event); } } @FXML protected void showHelps(Event event) { popEventMenu(event, HelpTools.colorHelps(true)); } @Override public boolean handleKeyEvent(KeyEvent event) { if (colorTab.isSelected()) { if (colorController.handleKeyEvent(event)) { return true; } } return super.handleKeyEvent(event); } /* static */ public static ColorQueryController open() { try { ColorQueryController controller = (ColorQueryController) WindowTools.openStage(Fxmls.ColorQueryFxml); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ColorsBlendController.java
released/MyBox/src/main/java/mara/mybox/controller/ColorsBlendController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Tab; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import mara.mybox.data.StringTable; import mara.mybox.db.data.ColorData; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.image.FxColorTools; import static mara.mybox.fxml.image.FxColorTools.color2css; import mara.mybox.image.data.PixelsBlend; import mara.mybox.image.data.PixelsBlendFactory; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2025-6-7 * @License Apache License Version 2.0 */ public class ColorsBlendController extends ColorQueryController { protected ColorData colorOverlay, colorBlended; protected String separator; @FXML protected Tab overlayTab, blendTab; @FXML protected ControlColorInput colorOverlayController; @FXML protected ControlColorsBlend blendController; public ColorsBlendController() { baseTitle = message("BlendColors"); } @Override public void initMore() { try { colorController.setParameter(baseName + "Base", Color.YELLOW); colorController.updateNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { goAction(); } }); colorOverlayController.setParameter(baseName + "Overlay", Color.SKYBLUE); colorOverlayController.updateNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { goAction(); } }); blendController.setParameters(this); blendController.changeNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { goAction(); } }); goAction(); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void okAction() { goAction(); } public boolean pickColors() { try { separator = pickSeparator(); if (separator == null || separator.isEmpty()) { popError(message("InvalidParamter") + ": " + message("ValueSeparator")); return false; } colorData = colorController.colorData; if (colorData == null || colorData.getRgba() == null) { popError(message("SelectToHandle") + ": " + message("BaseColor")); return false; } colorData = new ColorData(colorData.getRgba()) .setColorName(blendController.baseAboveCheck.isSelected() ? message("OverlayColor") : message("BaseColor")) .setvSeparator(separator).convert(); colorOverlay = colorOverlayController.colorData; if (colorOverlay == null || colorOverlay.getRgba() == null) { popError(message("SelectToHandle") + ": " + message("OverlayColor")); return false; } colorOverlay = new ColorData(colorOverlay.getRgba()) .setColorName(blendController.baseAboveCheck.isSelected() ? message("BaseColor") : message("OverlayColor")) .setvSeparator(separator).convert(); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @FXML @Override public void goAction() { try { if (!pickColors()) { return; } PixelsBlend blender = blendController.pickValues(-1f); if (blender == null) { popError(message("SelectToHandle") + ": " + message("BlendMode")); return; } colorBlended = new ColorData(blender.blend(colorOverlay.getColorValue(), colorData.getColorValue())) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); String html = "<html><body contenteditable=\"false\">\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<svg xmlns=\"http://www.w3.org/2000/svg\" height=\"400\" width=\"600\">\n" + " <circle cx=\"200\" cy=\"200\" fill=\"" + colorData.css() + "\" r=\"198\"/>\n" + " <circle cx=\"400\" cy=\"200\" fill=\"" + colorOverlay.css() + "\" r=\"198\"/>\n" + " <path d=\"M 299.50,372.34 A 199.00 199.00 0 0 0 300 28 A 199.00 199.00 0 0 0 300 372\" " + " fill=\"" + colorBlended.css() + "\" />\n" + "</svg>\n"; StringTable table = new StringTable(); List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(message("BlendMode"), blender.modeName())); table.add(row); row = new ArrayList<>(); row.addAll(Arrays.asList(message("Weight2"), blender.getWeight() + "")); table.add(row); html += table.div(); List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(message("Data"), message("Base"), message("Overlay"), message("BlendColors"))); table = new StringTable(names); table = blendController.baseAboveCheck.isSelected() ? FxColorTools.colorsTable(table, colorOverlay, colorData, colorBlended) : FxColorTools.colorsTable(table, colorData, colorOverlay, colorBlended); html += table.div(); html += "</body></html>"; htmlController.displayHtml(html); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void addColor() { if (colorBlended == null) { return; } ColorsManageController.addOneColor(colorBlended.getColor()); } @FXML public void demo() { if (!pickColors()) { return; } FxSingletonTask demoTask = new FxSingletonTask<Void>(this) { private String html; @Override protected boolean handle() { try { StringTable table = new StringTable(message("BlendColors")); List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(message("Color"), message("Name"), message("Weight"), message("BaseImageAboveOverlay"), message("Hue"), message("Saturation"), message("Brightness"), message("RYBAngle"), message("Opacity"), message("RGBA"), message("RGB"), message("sRGB"), message("HSBA"), message("CalculatedCMYK"), "Adobe RGB", "Apple RGB", "ECI RGB", "sRGB Linear", "Adobe RGB Linear", "Apple RGB Linear", "ECI CMYK", "Adobe CMYK Uncoated FOGRA29", "XYZ", "CIE-L*ab", "LCH(ab)", "CIE-L*uv", "LCH(uv)", message("Value"))); table.add(row); table.add(colorRow(colorData, -1, false)); table.add(colorRow(colorOverlay, -1, false)); PixelsBlend blender; PixelsBlend.ImagesBlendMode mode; int v1 = colorOverlay.getColorValue(), v2 = colorData.getColorValue(); for (String name : PixelsBlendFactory.blendModes()) { if (!isWorking()) { return false; } mode = PixelsBlendFactory.blendMode(name); blender = PixelsBlendFactory.create(mode).setBlendMode(mode); blender.setWeight(1.0F).setBaseAbove(false); ColorData blended = new ColorData(blender.blend(v1, v2)) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); table.add(colorRow(blended, 1.0f, false)); blender.setWeight(0.5F).setBaseAbove(false); blended = new ColorData(blender.blend(v1, v2)) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); table.add(colorRow(blended, 0.5f, false)); blender.setWeight(1.0F).setBaseAbove(true); blended = new ColorData(blender.blend(v1, v2)) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); table.add(colorRow(blended, 1.0f, true)); blender.setWeight(0.5F).setBaseAbove(true); blended = new ColorData(blender.blend(v1, v2)) .setColorName(blender.modeName()) .setvSeparator(separator).convert(); table.add(colorRow(blended, 0.5f, true)); } html = table.html(); return html != null; } catch (Exception e) { error = e.toString(); return false; } } protected List<String> colorRow(ColorData color, float weight, boolean above) { List<String> row = new ArrayList<>(); row.add("<DIV style=\"width: 50px; background-color:" + color2css(color.getColor()) + "; \">&nbsp;&nbsp;&nbsp;</DIV>"); row.addAll(Arrays.asList(color.getColorName(), weight >= 0 ? weight + "" : "", above ? message("Yes") : "", color.getHue(), color.getSaturation(), color.getBrightness(), color.getRybAngle(), color.getOpacity(), color.getRgba(), color.getRgb(), color.getSrgb(), color.getHsb(), color.getCalculatedCMYK(), color.getAdobeRGB(), color.getAppleRGB(), color.getEciRGB(), color.getSRGBLinear(), color.getAdobeRGBLinear(), color.getAppleRGBLinear(), color.getEciCMYK(), color.getAdobeCMYK(), color.getXyz(), color.getCieLab(), color.getLchab(), color.getCieLuv(), color.getLchuv(), color.getColorValue() + "")); return row; } @Override protected void whenSucceeded() { HtmlPopController.showHtml(myController, html); } }; start(demoTask); } @Override public boolean handleKeyEvent(KeyEvent event) { if (overlayTab.isSelected()) { if (colorOverlayController.handleKeyEvent(event)) { return true; } } else if (blendTab.isSelected()) { if (blendController.handleKeyEvent(event)) { return true; } } return super.handleKeyEvent(event); } /* static */ public static ColorsBlendController open() { try { ColorsBlendController controller = (ColorsBlendController) WindowTools.openStage(Fxmls.ColorsBlendFxml); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlImageScope.java
released/MyBox/src/main/java/mara/mybox/controller/ControlImageScope.java
package mara.mybox.controller; import java.util.Arrays; import javafx.beans.binding.Bindings; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.fxml.FXML; import javafx.scene.Cursor; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.control.Toggle; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.util.Callback; import mara.mybox.data.DoublePoint; import mara.mybox.db.table.TableColor; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.cell.ListColorCell; import mara.mybox.fxml.image.ImageViewTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.fxml.style.StyleTools; import mara.mybox.image.data.ImageScope.ShapeType; import static mara.mybox.image.data.ImageScope.ShapeType.Matting4; import static mara.mybox.image.data.ImageScope.ShapeType.Matting8; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2020-9-15 * @License Apache License Version 2.0 */ public class ControlImageScope extends ControlImageScope_Load { protected BaseImageController imageEditor; protected ControlDataImageScope dataEditor; public void setImageEditor(BaseImageController parent) { try { this.parentController = parent; imageEditor = parent; } catch (Exception e) { MyBoxLog.debug(e); } } public void setDataEditor(ControlDataImageScope parent) { try { parentController = parent; dataEditor = parent; } catch (Exception e) { MyBoxLog.debug(e); } } @Override public Image srcImage() { if (imageEditor != null) { image = imageEditor.imageView.getImage(); sourceFile = imageEditor.sourceFile; } else if (dataEditor != null) { image = dataEditor.srcImage; sourceFile = dataEditor.sourceFile; } return image; } @Override public void initControls() { try { super.initControls(); initOptions(); initShapeTab(); initColorsTab(); initMatchTab(); thisPane.disableProperty().bind(Bindings.isNull(imageView.imageProperty())); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(opacitySelector, new Tooltip(message("Opacity"))); } catch (Exception e) { MyBoxLog.debug(e); } } public void initOptions() { try { tableColor = new TableColor(); popShapeMenu = true; shapeStyle = null; needFixSize = true; showNotify = new SimpleBooleanProperty(false); changedNotify = new SimpleBooleanProperty(false); scopeExcludeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); handleTransparentCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); maskColorController.init(this, baseName + "MaskColor", Color.TRANSPARENT); maskColor = maskColorController.awtColor(); maskColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (!isSettingValues) { maskColor = maskColorController.awtColor(); scope.setMaskColor(maskColor); indicateScope(); } } }); maskOpacity = UserConfig.getFloat(baseName + "ScopeOpacity", 0.5f); opacitySelector.getItems().addAll( Arrays.asList("0.5", "0.2", "1", "0", "0.8", "0.3", "0.6", "0.7", "0.9", "0.4") ); opacitySelector.setValue(maskOpacity + ""); opacitySelector.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldVal, String newVal) { try { if (isSettingValues || newVal == null) { return; } float f = Float.parseFloat(newVal); if (f >= 0 && f <= 1.0) { maskOpacity = f; ValidationTools.setEditorNormal(opacitySelector); UserConfig.setFloat(baseName + "ScopeOpacity", f); scope.setMaskOpacity(maskOpacity); indicateScope(); } else { ValidationTools.setEditorBadStyle(opacitySelector); } } catch (Exception e) { ValidationTools.setEditorBadStyle(opacitySelector); } } }); clearDataWhenLoadImageCheck.setSelected(UserConfig.getBoolean(baseName + "ClearDataWhenLoadImage", true)); clearDataWhenLoadImageCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal) { if (!isSettingValues) { UserConfig.setBoolean(baseName + "ClearDataWhenLoadImage", clearDataWhenLoadImageCheck.isSelected()); } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void initShapeTab() { try { tabPane.getTabs().remove(controlsTab); shapeTypeGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue ov, Toggle oldValue, Toggle newValue) { if (!isSettingValues) { pickScope(); changedNotify.set(!changedNotify.get()); } } }); shapeExcludedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); pointsController.tableData.addListener(new ListChangeListener<DoublePoint>() { @Override public void onChanged(ListChangeListener.Change<? extends DoublePoint> c) { if (isSettingValues || pointsController.isSettingValues || pointsController.isSettingTable) { return; } indicateScope(); changedNotify.set(!changedNotify.get()); } }); outlineController.setParameter(this, StyleTools.getIconFile("iconAdd.png").toString(), null); outlineController.notify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { indicateOutline(true); changedNotify.set(!changedNotify.get()); } }); } catch (Exception e) { MyBoxLog.error(e); } } public void initColorsTab() { try { colorsList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); colorsList.setCellFactory(new Callback<ListView<Color>, ListCell<Color>>() { @Override public ListCell<Color> call(ListView<Color> p) { return new ListColorCell(); } }); deleteColorsButton.disableProperty().bind(colorsList.getSelectionModel().selectedItemProperty().isNull()); saveColorsButton.disableProperty().bind(colorsList.getSelectionModel().selectedItemProperty().isNull()); colorController.init(this, baseName + "Color", Color.GOLD); colorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { addColor((Color) colorController.rect.getFill()); changedNotify.set(!changedNotify.get()); } }); colorExcludedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void initMatchTab() { try { matchController.changeNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (!isSettingValues) { indicateScope(); changedNotify.set(!changedNotify.get()); } } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean afterImageLoaded() { if (super.afterImageLoaded()) { if (UserConfig.getBoolean(baseName + "ClearDataWhenLoadImage", true)) { pointsController.isSettingValues = true; pointsController.tableData.clear(); pointsController.isSettingValues = false; isSettingValues = true; colorsList.getItems().clear(); isSettingValues = false; if (scope != null) { scope.resetParameters(); } } pickScope(); return true; } else { return false; } } @Override public void fitView() { } @FXML @Override public void createAction() { if (!checkBeforeNextAction()) { return; } ImageCanvasInputController controller = ImageCanvasInputController.open(this, baseTitle); controller.notify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { Image canvas = controller.getCanvas(); if (canvas != null) { loadImage(canvas); } controller.close(); } }); } @FXML @Override public boolean popAction() { ImageScopeViewsController.open(this); return true; } @FXML @Override public void refreshAction() { isSettingValues = false; indicateScope(); } @FXML @Override public boolean withdrawAction() { if (scope == null || isSettingValues) { return false; } try { switch (scope.getShapeType()) { case Matting4: case Matting8: case Polygon: pointsController.removeLastItem(); return true; } return false; } catch (Exception e) { } return false; } @FXML @Override public void clearAction() { if (scope == null || isSettingValues) { return; } try { switch (scope.getShapeType()) { case Matting4: case Matting8: case Polygon: pointsController.clear(); break; case Whole: clearColors(); break; } } catch (Exception e) { } } @Override public void paneClicked(MouseEvent event, DoublePoint p) { if (p == null || imageView.getImage() == null) { imageView.setCursor(Cursor.OPEN_HAND); return; } if (isPickingColor) { Color color = ImageViewTools.imagePixel(p, srcImage()); if (color != null) { addColor(color); changedNotify.set(!changedNotify.get()); } } else if (event.getClickCount() == 1) { if (event.getButton() == MouseButton.PRIMARY) { if (addPointWhenClick) { if (scope.getShapeType() == ShapeType.Matting4 || scope.getShapeType() == ShapeType.Matting8) { int x = (int) Math.round(p.getX()); int y = (int) Math.round(p.getY()); isSettingValues = true; pointsController.addPoint(x, y); isSettingValues = false; indicateScope(); changedNotify.set(!changedNotify.get()); } else if (scope.getShapeType() == ShapeType.Polygon && !maskControlDragged) { maskPolygonData.add(p.getX(), p.getY()); maskShapeDataChanged(); changedNotify.set(!changedNotify.get()); } } } else if (event.getButton() == MouseButton.SECONDARY) { popEventMenu(event, maskShapeMenu(event, currentMaskShapeData(), p)); } } maskControlDragged = false; } @Override public void maskShapeDataChanged() { try { if (isSettingValues || !isValidScope()) { return; } switch (scope.getShapeType()) { case Rectangle: rectLeftTopXInput.setText(scale(maskRectangleData.getX(), 2) + ""); rectLeftTopYInput.setText(scale(maskRectangleData.getY(), 2) + ""); rightBottomXInput.setText(scale(maskRectangleData.getMaxX(), 2) + ""); rightBottomYInput.setText(scale(maskRectangleData.getMaxY(), 2) + ""); scope.setRectangle(maskRectangleData.copy()); break; case Ellipse: rectLeftTopXInput.setText(scale(maskEllipseData.getX(), 2) + ""); rectLeftTopYInput.setText(scale(maskEllipseData.getY(), 2) + ""); rightBottomXInput.setText(scale(maskEllipseData.getMaxX(), 2) + ""); rightBottomYInput.setText(scale(maskEllipseData.getMaxY(), 2) + ""); scope.setEllipse(maskEllipseData.copy()); break; case Circle: circleCenterXInput.setText(scale(maskCircleData.getCenterX(), 2) + ""); circleCenterYInput.setText(scale(maskCircleData.getCenterY(), 2) + ""); circleRadiusInput.setText(scale(maskCircleData.getRadius(), 2) + ""); scope.setCircle(maskCircleData.copy()); break; case Polygon: pointsController.loadList(maskPolygonData.getPoints()); scope.setPolygon(maskPolygonData.copy()); break; case Outline: scope.setRectangle(maskRectangleData.copy()); } indicateScope(); changedNotify.set(!changedNotify.get()); } catch (Exception e) { MyBoxLog.error(e); } } @Override protected void checkPickingColor() { if (!tabPane.getTabs().contains(colorsTab)) { isPickingColor = false; } if (isPickingColor) { tabPane.getSelectionModel().select(colorsTab); } super.checkPickingColor(); } @FXML public void aboutScope() { openHtml(HelpTools.aboutImageScope()); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlImageText.java
released/MyBox/src/main/java/mara/mybox/controller/ControlImageText.java
package mara.mybox.controller; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.sql.Connection; import java.util.Arrays; import java.util.List; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import mara.mybox.image.data.PixelsBlend; import mara.mybox.data.ShapeStyle; import mara.mybox.db.DerbyBase; import mara.mybox.db.table.TableStringValues; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-9-10 * @License Apache License Version 2.0 */ public class ControlImageText extends BaseController { protected int margin, rowHeight, x, y, fontSize, shadow, angle, baseX, baseY, textY, textWidth, textHeight, bordersStrokeWidth, bordersArc, bordersMargin; protected String text, fontFamily, fontName; protected FontPosture fontPosture; protected FontWeight fontWeight; protected PixelsBlend blend; protected ShapeStyle borderStyle; @FXML protected TextArea textArea; @FXML protected TextField xInput, yInput, marginInput, bordersMarginInput; @FXML protected ComboBox<String> rowHeightSelector, fontSizeSelector, fontStyleSelector, fontFamilySelector, angleSelector, shadowSelector, bordersStrokeWidthSelector, bordersArcSelector; @FXML protected CheckBox outlineCheck, verticalCheck, rightToLeftCheck, bordersCheck, bordersFillCheck, bordersStrokeDottedCheck; @FXML protected ControlColorSet fontColorController, shadowColorController, bordersFillColorController, bordersStrokeColorController; @FXML protected ToggleGroup positionGroup; @FXML protected RadioButton rightBottomRadio, rightTopRadio, leftBottomRadio, leftTopRadio, centerRadio, customRadio; @FXML protected ControlColorsBlend blendController; @FXML protected VBox bordersBox; @FXML protected Label sizeLabel; public void setParameters(BaseController parent) { parentController = parent; baseName = parentController.baseName; try (Connection conn = DerbyBase.getConnection()) { initText(conn); initStyle(conn); initBorders(conn); initPosition(conn); blendController.setParameters(conn, parent); } catch (Exception e) { MyBoxLog.error(e); } } public void initText(Connection conn) { try { textArea.setText(UserConfig.getString(conn, baseName + "TextValue", "MyBox")); } catch (Exception e) { MyBoxLog.error(e); } } public void initPosition(Connection conn) { try { margin = UserConfig.getInt(conn, baseName + "Margin", 20); marginInput.setText(margin + ""); positionGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { checkPositionType(); } }); checkPositionType(); } catch (Exception e) { MyBoxLog.error(e); } } public boolean checkPositionType() { xInput.setDisable(true); yInput.setDisable(true); marginInput.setDisable(true); if (rightBottomRadio.isSelected()) { marginInput.setDisable(false); } else if (rightTopRadio.isSelected()) { marginInput.setDisable(false); } else if (leftBottomRadio.isSelected()) { marginInput.setDisable(false); } else if (leftTopRadio.isSelected()) { marginInput.setDisable(false); } else if (centerRadio.isSelected()) { } else if (customRadio.isSelected()) { xInput.setDisable(false); yInput.setDisable(false); } return true; } public void initStyle(Connection conn) { try { rowHeight = UserConfig.getInt(conn, baseName + "TextRowHeight", -1); List<String> heights = Arrays.asList( message("Automatic"), "18", "15", "9", "10", "12", "14", "17", "24", "36", "48", "64", "96"); rowHeightSelector.getItems().addAll(heights); if (rowHeight <= 0) { rowHeightSelector.setValue(message("Automatic")); } else { rowHeightSelector.setValue(rowHeight + ""); } fontColorController.setConn(conn).init(this, baseName + "TextColor", Color.ORANGE); fontFamilySelector.getItems().addAll(javafx.scene.text.Font.getFamilies()); fontFamily = UserConfig.getString(conn, baseName + "TextFontFamily", "Arial"); fontFamilySelector.getSelectionModel().select(fontFamily); fontWeight = FontWeight.NORMAL; fontPosture = FontPosture.REGULAR; List<String> styles = Arrays.asList(message("Regular"), message("Bold"), message("Italic"), message("Bold Italic")); fontStyleSelector.getItems().addAll(styles); fontStyleSelector.getSelectionModel().select(0); List<String> sizes = Arrays.asList( "72", "18", "15", "9", "10", "12", "14", "17", "24", "36", "48", "64", "96"); fontSizeSelector.getItems().addAll(sizes); fontSize = UserConfig.getInt(conn, baseName + "TextFontSize", 72); fontSizeSelector.getSelectionModel().select(fontSize + ""); shadowSelector.getItems().addAll(Arrays.asList("0", "4", "5", "3", "2", "1", "6")); shadow = UserConfig.getInt(conn, baseName + "TextShadow", 0); shadowSelector.getSelectionModel().select(shadow + ""); shadowColorController.setConn(conn).init(this, baseName + "ShadowColor", Color.GREY); angleSelector.getItems().addAll(Arrays.asList("0", "90", "180", "270", "45", "135", "225", "315", "60", "150", "240", "330", "15", "105", "195", "285", "30", "120", "210", "300")); angle = UserConfig.getInt(conn, baseName + "TextAngle", 0); angleSelector.getSelectionModel().select(angle + ""); outlineCheck.setSelected(UserConfig.getBoolean(conn, baseName + "TextOutline", false)); verticalCheck.setSelected(UserConfig.getBoolean(conn, baseName + "TextVertical", false)); rightToLeftCheck.setSelected(UserConfig.getBoolean(conn, baseName + "TextRightToLeft", false)); rightToLeftCheck.visibleProperty().bind(verticalCheck.selectedProperty()); } catch (Exception e) { MyBoxLog.error(e); } } public void initBorders(Connection conn) { try { bordersBox.disableProperty().bind(bordersCheck.selectedProperty().not()); bordersCheck.setSelected(UserConfig.getBoolean(conn, baseName + "Borders", true)); bordersFillCheck.setSelected(UserConfig.getBoolean(conn, baseName + "BordersFill", true)); bordersFillColorController.setConn(conn).init(this, baseName + "BordersFillColor", Color.WHITE); bordersStrokeColorController.setConn(conn).init(this, baseName + "BordersStrokeColor", Color.WHITE); bordersStrokeWidth = UserConfig.getInt(conn, baseName + "BordersStrokeWidth", 0); if (bordersStrokeWidth < 0) { bordersStrokeWidth = 0; } bordersStrokeWidthSelector.getItems().addAll(Arrays.asList("0", "1", "2", "4", "3", "5", "10", "6")); bordersStrokeWidthSelector.setValue(bordersStrokeWidth + ""); bordersStrokeDottedCheck.setSelected(UserConfig.getBoolean(conn, baseName + "BordersStrokeDotted", false)); bordersArc = UserConfig.getInt(conn, baseName + "BordersArc", 0); if (bordersArc < 0) { bordersArc = 0; } bordersArcSelector.getItems().addAll(Arrays.asList( "0", "3", "5", "2", "1", "8", "10", "15", "20", "30", "48", "64", "96")); bordersArcSelector.setValue(bordersArc + ""); bordersMargin = UserConfig.getInt(conn, baseName + "BordersMargin", 10); bordersMarginInput.setText(bordersMargin + ""); } catch (Exception e) { MyBoxLog.error(e); } } public boolean checkText() { text = text(); if (text == null || text.isEmpty()) { popError(message("InvalidParameters") + ": " + message("Text")); return false; } return true; } public boolean checkLocation() { if (customRadio.isSelected()) { try { x = Integer.parseInt(xInput.getText().trim()); } catch (Exception e) { popError(message("InvalidParameters") + ": x"); return false; } try { y = Integer.parseInt(yInput.getText().trim()); } catch (Exception e) { popError(message("InvalidParameters") + ": y"); return false; } } if (!marginInput.isDisable()) { try { margin = Integer.parseInt(marginInput.getText().trim()); } catch (Exception e) { popError(message("InvalidParameters") + ": y" + message("Margins")); return false; } } return true; } public boolean checkStyle() { try { String s = rowHeightSelector.getValue(); if (message("Automatic").equals(s)) { rowHeight = -1; } else { int v = Integer.parseInt(s); if (v >= 0) { rowHeight = v; } else { rowHeight = -1; } } } catch (Exception e) { popError(message("InvalidParameters") + ": " + message("RowHeightPx")); return false; } fontFamily = fontFamilySelector.getValue(); String s = fontStyleSelector.getValue(); if (message("Bold").equals(s)) { fontWeight = FontWeight.BOLD; fontPosture = FontPosture.REGULAR; } else if (message("Italic").equals(s)) { fontWeight = FontWeight.NORMAL; fontPosture = FontPosture.ITALIC; } else if (message("Bold Italic").equals(s)) { fontWeight = FontWeight.BOLD; fontPosture = FontPosture.ITALIC; } else { fontWeight = FontWeight.NORMAL; fontPosture = FontPosture.REGULAR; } int v = -1; try { v = Integer.parseInt(fontSizeSelector.getValue()); } catch (Exception e) { } if (v > 0) { fontSize = v; } else { popError(message("InvalidParameters") + ": " + message("FontSize")); return false; } v = -1; try { v = Integer.parseInt(shadowSelector.getValue()); } catch (Exception e) { } if (v >= 0) { shadow = v; } else { popError(message("InvalidParameters") + ": " + message("Shadow")); return false; } v = -1; try { v = Integer.parseInt(angleSelector.getValue()); } catch (Exception e) { } if (v >= 0) { angle = v; } else { popError(message("InvalidParameters") + ": " + message("Angle")); return false; } return true; } public boolean checkBorders() { int v = -1; try { v = Integer.parseInt(bordersMarginInput.getText()); } catch (Exception e) { } if (v < 0) { popError(message("InvalidParameters") + ": " + message("BordersMargin")); return false; } bordersMargin = v; v = -1; try { v = Integer.parseInt(bordersStrokeWidthSelector.getValue()); } catch (Exception e) { } if (v < 0) { popError(message("InvalidParameters") + ": " + message("StrokeWidth")); return false; } bordersStrokeWidth = v; v = -1; try { v = Integer.parseInt(bordersArcSelector.getValue()); } catch (Exception e) { } if (v < 0) { popError(message("InvalidParameters") + ": " + message("Arc")); return false; } bordersArc = v; return true; } public boolean checkBlend() { return blendController.checkValues(); } public boolean checkValues() { return checkText() && checkLocation() && checkStyle() && checkBorders() && checkBlend(); } public boolean pickValues() { blend = null; borderStyle = null; try (Connection conn = DerbyBase.getConnection()) { conn.setAutoCommit(false); UserConfig.setString(conn, baseName + "TextValue", text); TableStringValues.add(conn, "ImageTextHistories", text); UserConfig.setInt(conn, baseName + "TextRowHeight", rowHeight); UserConfig.setInt(conn, baseName + "TextAngle", angle); UserConfig.setInt(conn, baseName + "TextShadow", shadow); UserConfig.setString(conn, baseName + "TextFontFamily", fontFamily); UserConfig.setInt(conn, baseName + "TextFontSize", fontSize); UserConfig.setInt(conn, baseName + "Margin", margin); UserConfig.setBoolean(conn, baseName + "TextOutline", outlineCheck.isSelected()); UserConfig.setBoolean(conn, baseName + "TextVertical", verticalCheck.isSelected()); UserConfig.setBoolean(conn, baseName + "TextRightToLeft", rightToLeftCheck.isSelected()); UserConfig.setInt(conn, baseName + "BordersArc", bordersArc); UserConfig.setInt(conn, baseName + "BordersStrokeWidth", bordersStrokeWidth); UserConfig.setInt(conn, baseName + "BordersMargin", bordersMargin); UserConfig.setBoolean(conn, baseName + "BordersFill", bordersFillCheck.isSelected()); UserConfig.setBoolean(conn, baseName + "BordersStrokeDotted", bordersStrokeDottedCheck.isSelected()); UserConfig.setBoolean(conn, baseName + "Borders", bordersCheck.isSelected()); blend = blendController.pickValues(conn); if (bordersCheck.isSelected()) { borderStyle = new ShapeStyle(conn, "Text") .setStrokeColor(bordersStrokeColorController.color()) .setStrokeWidth(bordersStrokeWidth) .setIsFillColor(bordersFillCheck.isSelected()) .setFillColor(bordersFillColorController.color()) .setStrokeDashed(bordersStrokeDottedCheck.isSelected()); } conn.commit(); } catch (Exception e) { MyBoxLog.error(e); return false; } return blend != null; } public void setLocation(double x, double y) { xInput.setText((int) x + ""); yInput.setText((int) y + ""); customRadio.setSelected(true); } public void countValues(Graphics2D g, FontMetrics metrics, double imageWidth, double imageHeight) { countTextBound(g, metrics); if (rightBottomRadio.isSelected()) { baseX = (int) imageWidth - margin - textWidth; baseY = (int) imageHeight - margin - textHeight; } else if (rightTopRadio.isSelected()) { baseX = (int) imageWidth - margin - textWidth; baseY = margin; } else if (leftBottomRadio.isSelected()) { baseX = margin; baseY = (int) imageHeight - margin - textHeight; } else if (leftTopRadio.isSelected()) { baseX = margin; baseY = margin; } else if (centerRadio.isSelected()) { baseX = (int) ((imageWidth - textWidth) / 2); baseY = (int) ((imageHeight - textHeight) / 2); } else if (customRadio.isSelected()) { baseX = x; baseY = y; } else { baseX = 0; baseY = 0; } textY = baseY + metrics.getAscent(); } public void countTextBound(Graphics2D g, FontMetrics metrics) { String[] lines = text().split("\n", -1); int lend = lines.length - 1, heightMax = 0, charWidthMax = 0; textWidth = 0; textHeight = 0; if (isVertical()) { for (int r = 0; r <= lend; r++) { String line = lines[r]; int rHeight = 0; charWidthMax = 0; for (int i = 0; i < line.length(); i++) { String c = line.charAt(i) + ""; Rectangle2D cBound = metrics.getStringBounds(c, g); rHeight += (int) cBound.getHeight(); if (rowHeight <= 0) { int charWidth = (int) cBound.getWidth(); if (charWidth > charWidthMax) { charWidthMax = charWidth; } } } if (rowHeight > 0) { textWidth += rowHeight; } else { textWidth += charWidthMax; } if (rHeight > heightMax) { heightMax = rHeight; } } textHeight = heightMax; } else { for (String line : lines) { Rectangle2D sBound = metrics.getStringBounds(line, g); if (rowHeight > 0) { textHeight += rowHeight; } else { textHeight += sBound.getHeight(); } int sWidth = (int) sBound.getWidth(); if (sWidth > charWidthMax) { charWidthMax = sWidth; } } textWidth = charWidthMax; } if (parentController instanceof ImageEditorController) { Platform.runLater(new Runnable() { @Override public void run() { sizeLabel.setText(message("TextSize") + ": " + textWidth + "x" + textHeight); } }); } } @FXML protected void showTextHistories(Event event) { PopTools.popSavedValues(this, textArea, event, "ImageTextHistories"); } @FXML public void popTextHistories(Event event) { if (UserConfig.getBoolean("ImageTextHistoriesPopWhenMouseHovering", false)) { showTextHistories(event); } } /* refer */ public String text() { return textArea.getText(); } public Font font() { if (fontWeight == FontWeight.BOLD) { if (fontPosture == FontPosture.REGULAR) { return new java.awt.Font(fontFamily, java.awt.Font.BOLD, fontSize); } else { return new java.awt.Font(fontFamily, java.awt.Font.BOLD + java.awt.Font.ITALIC, fontSize); } } else { if (fontPosture == FontPosture.REGULAR) { return new java.awt.Font(fontFamily, java.awt.Font.PLAIN, fontSize); } else { return new java.awt.Font(fontFamily, java.awt.Font.ITALIC, fontSize); } } } public javafx.scene.text.Font fxFont() { if (fontWeight == FontWeight.BOLD) { if (fontPosture == FontPosture.REGULAR) { return javafx.scene.text.Font.font(fontFamily, FontWeight.BOLD, FontPosture.REGULAR, fontSize); } else { return javafx.scene.text.Font.font(fontFamily, FontWeight.BOLD, FontPosture.ITALIC, fontSize); } } else { if (fontPosture == FontPosture.REGULAR) { return javafx.scene.text.Font.font(fontFamily, FontWeight.NORMAL, FontPosture.REGULAR, fontSize); } else { return javafx.scene.text.Font.font(fontFamily, FontWeight.NORMAL, FontPosture.ITALIC, fontSize); } } } public java.awt.Color textColor() { return fontColorController.awtColor(); } public java.awt.Color shadowColor() { return shadowColorController.awtColor(); } public boolean isVertical() { return verticalCheck.isSelected(); } public boolean isLeftToRight() { return !rightToLeftCheck.isSelected(); } public boolean isOutline() { return outlineCheck.isSelected(); } public PixelsBlend getBlend() { return blend; } public ShapeStyle getBorderStyle() { return borderStyle; } public boolean showBorders() { return bordersCheck.isSelected(); } public boolean bordersDotted() { return bordersStrokeDottedCheck.isSelected(); } public boolean bordersFilled() { return bordersFillCheck.isSelected(); } public java.awt.Color bordersStrokeColor() { return bordersStrokeColorController.awtColor(); } public java.awt.Color bordersFillColor() { return bordersFillColorController.awtColor(); } /* get */ public int getRowHeight() { return rowHeight; } public int getX() { return x; } public int getY() { return y; } public int getFontSize() { return fontSize; } public int getShadow() { return shadow; } public int getAngle() { return angle; } public String getFontFamily() { return fontFamily; } public String getFontName() { return fontName; } public int getMargin() { return margin; } public int getBaseX() { return baseX; } public int getBaseY() { return baseY; } public int getTextWidth() { return textWidth; } public int getTextHeight() { return textHeight; } public int getTextY() { return textY; } public int getBordersStrokeWidth() { return bordersStrokeWidth; } public int getBordersArc() { return bordersArc; } public int getBordersMargin() { return bordersMargin; } /* set */ public ControlImageText setBlend(PixelsBlend blend) { this.blend = blend; return this; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/Data2DExportController.java
released/MyBox/src/main/java/mara/mybox/controller/Data2DExportController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.Tab; import javafx.scene.layout.VBox; import mara.mybox.data2d.operate.Data2DExport; import mara.mybox.data2d.tools.Data2DColumnTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.SoundTools; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.DateTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-12-8 * @License Apache License Version 2.0 */ public class Data2DExportController extends BaseData2DTaskController { protected Data2DExport export; protected String filePrefix; @FXML protected BaseData2DRowsColumnsController rowsColumnsController; @FXML protected VBox dataBox, filterVBox, formatVBox, targetVBox; @FXML protected ControlDataExport convertController; @FXML protected Tab targetTab; @FXML protected CheckBox displayedNameCheck; public Data2DExportController() { baseTitle = message("Export"); } @Override public void initValues() { try { super.initValues(); sourceController = rowsColumnsController; formatValuesCheck = convertController.formatValuesCheck; rowNumberCheck = convertController.rowNumberCheck; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setParameters(BaseData2DLoadController controller) { try { super.setParameters(controller); convertController.setParameters(this); displayedNameCheck.setSelected(UserConfig.getBoolean(baseName + "ExportLabelAsColumn", true)); displayedNameCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } UserConfig.setBoolean(baseName + "ExportLabelAsColumn", displayedNameCheck.isSelected()); } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean checkOptions() { try { if (isSettingValues) { return true; } if (!super.checkOptions()) { return false; } targetPath = targetPathController.pickFile(); if (targetPath == null) { popError(message("InvalidParameters") + ": " + message("TargetPath")); tabPane.getSelectionModel().select(targetTab); return false; } filePrefix = data2D.getName(); if (filePrefix == null || filePrefix.isBlank()) { filePrefix = DateTools.nowFileString(); } export = convertController.pickParameters(data2D); export.setPathController(targetPathController) .setColumns(checkedColumns) .setColumnNames(Data2DColumnTools.toNames(checkedColumns, displayedNameCheck.isSelected())) .setInvalidAs(invalidAs) .setController(this); return export.initExport(filePrefix); } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public void beforeTask() { try { super.beforeTask(); dataBox.setDisable(true); filterVBox.setDisable(true); formatVBox.setDisable(true); targetVBox.setDisable(true); } catch (Exception e) { MyBoxLog.error(e); } } @Override protected void startOperation() { if (task != null) { task.cancel(); } taskSuccessed = false; task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { try { data2D.startTask(task, filterController.filter); if (!isAllPages() || !data2D.isMutiplePages()) { List<Integer> filteredRowsIndices = sourceController.filteredRowsIndices; export.openWriters(); for (Integer row : filteredRowsIndices) { List<String> dataRow = sourceController.tableData.get(row); List<String> exportRow = new ArrayList<>(); for (Integer col : checkedColsIndices) { exportRow.add(dataRow.get(col + 1)); } export.writeRow(exportRow); } export.end(); } else { export.setCols(checkedColsIndices).setTask(task).start(); } taskSuccessed = !export.isFailed(); return taskSuccessed; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { afterSuccess(); } @Override protected void finalAction() { super.finalAction(); closeTask(ok); } }; start(task, false); } @Override public void afterSuccess() { try { SoundTools.miao3(); if (openCheck.isSelected()) { export.openResults(); } if (targetPath != null && targetPath.exists()) { browseURI(targetPath.toURI()); recordFileOpened(targetPath); } else { popInformation(message("NoFileGenerated")); } } catch (Exception e) { MyBoxLog.error(e); } } @Override public void closeTask(boolean ok) { try { if (export != null) { export.end(); export = null; } super.closeTask(ok); dataBox.setDisable(false); filterVBox.setDisable(false); formatVBox.setDisable(false); targetVBox.setDisable(false); } catch (Exception e) { MyBoxLog.error(e); } } /* static */ public static Data2DExportController open(BaseData2DLoadController tableController) { try { Data2DExportController controller = (Data2DExportController) WindowTools.referredStage( tableController, Fxmls.Data2DExportFxml); controller.setParameters(tableController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BaseImageController_Base.java
released/MyBox/src/main/java/mara/mybox/controller/BaseImageController_Base.java
package mara.mybox.controller; import javafx.beans.property.SimpleBooleanProperty; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import mara.mybox.image.data.ImageAttributes; import mara.mybox.image.data.ImageInformation; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.ImageViewTools; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.LocateTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileTools; import mara.mybox.tools.StringTools; import static mara.mybox.value.AppVariables.sceneFontSize; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-8-10 * @License Apache License Version 2.0 */ public abstract class BaseImageController_Base extends BaseFileController { protected ImageInformation imageInformation; protected Image image; protected ImageAttributes attributes; protected final SimpleBooleanProperty loadNotify, sizeNotify; protected boolean imageChanged, isPickingColor, backgroundLoad; protected int loadWidth, defaultLoadWidth, framesNumber, frameIndex, // 0-based sizeChangeAware, zoomStep, xZoomStep, yZoomStep; protected FxTask loadTask; protected double mouseX, mouseY; protected ColorsPickingController paletteController; @FXML protected VBox imageBox; @FXML protected ScrollPane scrollPane; @FXML protected AnchorPane maskPane; @FXML protected ImageView imageView; @FXML protected Rectangle borderLine; @FXML protected Text sizeText, xyText; @FXML protected Label imageLabel; @FXML protected Button imageSizeButton, paneSizeButton, zoomInButton, zoomOutButton, selectPixelsButton; @FXML protected CheckBox pickColorCheck, rulerXCheck, gridCheck, coordinateCheck; @FXML protected ComboBox<String> zoomStepSelector, loadWidthSelector; public BaseImageController_Base() { loadNotify = new SimpleBooleanProperty(false); sizeNotify = new SimpleBooleanProperty(false); } public void notifyLoad() { loadNotify.set(!loadNotify.get()); } public void notifySize() { sizeNotify.set(!sizeNotify.get()); } public void fitSize() { if (scrollPane == null || imageView == null || imageView.getImage() == null) { return; } try { if (scrollPane.getHeight() < imageHeight() || scrollPane.getWidth() < imageWidth()) { paneSize(); } else { loadedSize(); } } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void paneSize() { if (imageView == null || imageView.getImage() == null || scrollPane == null) { return; } try { ImageViewTools.paneSize(scrollPane, imageView); refinePane(); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void loadedSize() { if (imageView == null || imageView.getImage() == null || scrollPane == null) { return; } try { ImageViewTools.imageSize(scrollPane, imageView); refinePane(); } catch (Exception e) { MyBoxLog.error(e); } } protected void popContextMenu(double x, double y) { if (imageView == null || imageView.getImage() == null) { return; } MenuImageViewController.imageViewMenu((BaseImageController) this, x, y); } /* status */ protected void zoomStepChanged() { xZoomStep = zoomStep; yZoomStep = zoomStep; } protected void setZoomStep(Image image) { if (image == null) { return; } zoomStep = (int) image.getWidth() / 10; if (zoomStepSelector != null) { zoomStepSelector.setValue(zoomStep + ""); } else { xZoomStep = (int) image.getWidth() / 10; yZoomStep = (int) image.getHeight() / 10; } } public void viewSizeChanged(double change) { if (isSettingValues || change < sizeChangeAware || imageView == null || imageView.getImage() == null) { return; } refinePane(); notifySize(); } public void paneSizeChanged(double change) { viewSizeChanged(change); } public void refinePane() { if (isSettingValues || scrollPane == null || imageView == null || imageView.getImage() == null) { return; } LocateTools.moveCenter(scrollPane, imageView); scrollPane.setVvalue(scrollPane.getVmin()); updateLabelsTitle(); } public synchronized void updateLabelsTitle() { try { updateStageTitle(); updateImageLabel(); updateSizeLabel(); } catch (Exception e) { MyBoxLog.debug(e); } } public void updateStageTitle() { try { if (getMyStage() == null || !isTopPane) { return; } myStage.setTitle(getBaseTitle() + fileTitle()); } catch (Exception e) { MyBoxLog.debug(e); } } public String fileTitle() { try { String title; if (sourceFile != null) { title = " " + sourceFile.getAbsolutePath(); if (framesNumber > 1 && frameIndex >= 0) { title += " - " + message("Frame") + " " + (frameIndex + 1); } if (imageInformation != null && imageInformation.isIsScaled()) { title += " - " + message("Scaled"); } } else { title = ""; } if (imageChanged) { title += " " + "*"; } return title; } catch (Exception e) { MyBoxLog.debug(e); return ""; } } public void updateImageLabel() { try { if (imageLabel == null) { return; } String imageInfo = "", fileInfo = "", loadInfo = ""; if (sourceFile != null) { fileInfo = message("File") + ":" + sourceFile.getAbsolutePath() + "\n" + message("FileSize") + ":" + FileTools.showFileSize(sourceFile.length()) + "\n" + message("ModifyTime") + ":" + DateTools.datetimeToString(sourceFile.lastModified()); } if (framesNumber > 1) { imageInfo = message("FramesNumber") + ":" + framesNumber + "\n"; if (frameIndex >= 0) { imageInfo += message("CurrentFrame") + ":" + (frameIndex + 1) + "\n"; } } if (imageInformation != null) { imageInfo += message("Format") + ":" + imageInformation.getImageFormat() + "\n" + message("Pixels") + ":" + (int) imageInformation.getWidth() + "x" + (int) imageInformation.getHeight(); if (imageInformation.isIsScaled()) { imageInfo += "\n" + message("Scaled"); } } else if (imageView != null && imageView.getImage() != null) { imageInfo += message("Pixels") + ":" + (int) imageView.getImage().getWidth() + "x" + (int) imageView.getImage().getHeight(); } if (imageView != null && imageView.getImage() != null) { loadInfo = message("LoadedSize") + ":" + (int) imageView.getImage().getWidth() + "x" + (int) imageView.getImage().getHeight() + "\n" + message("DisplayedSize") + ":" + (int) imageView.getBoundsInParent().getWidth() + "x" + (int) imageView.getBoundsInParent().getHeight(); } String more = moreDisplayInfo(); loadInfo += (!loadInfo.isBlank() && !more.isBlank() ? "\n" : "") + more; if (imageChanged) { loadInfo += "\n" + message("ImageChanged"); } String finalInfo = fileInfo + "\n" + imageInfo + "\n" + loadInfo; imageLabel.setText(StringTools.replaceLineBreak(finalInfo)); } catch (Exception e) { MyBoxLog.debug(e); } } public void updateSizeLabel() { try { if (imageView == null || imageView.getImage() == null) { return; } if (borderLine != null) { borderLine.setLayoutX(imageView.getLayoutX() - 1); borderLine.setLayoutY(imageView.getLayoutY() - 1); borderLine.setWidth(viewWidth() + 2); borderLine.setHeight(viewHeight() + 2); } if (sizeText != null) { sizeText.setText((int) (imageView.getImage().getWidth()) + "x" + (int) (imageView.getImage().getHeight())); sizeText.setTextAlignment(TextAlignment.LEFT); if (imageView.getImage().getWidth() >= imageView.getImage().getHeight()) { sizeText.setX(borderLine.getBoundsInParent().getMinX()); sizeText.setY(borderLine.getBoundsInParent().getMinY() - sceneFontSize - 1); } else { sizeText.setX(borderLine.getBoundsInParent().getMinX() - sizeText.getBoundsInParent().getWidth() - sceneFontSize); sizeText.setY(borderLine.getBoundsInParent().getMaxY() - sceneFontSize - 1); } } } catch (Exception e) { MyBoxLog.debug(e); } } protected String moreDisplayInfo() { return ""; } /* values */ public double imageWidth() { if (imageView != null && imageView.getImage() != null) { return imageView.getImage().getWidth(); } else if (image != null) { return image.getWidth(); } else if (imageInformation != null) { return imageInformation.getWidth(); } else { return -1; } } public double imageHeight() { if (imageView != null && imageView.getImage() != null) { return imageView.getImage().getHeight(); } else if (image != null) { return image.getHeight(); } else if (imageInformation != null) { return imageInformation.getHeight(); } else { return -1; } } public double viewWidth() { return imageView.getBoundsInParent().getWidth(); } public double viewHeight() { return imageView.getBoundsInParent().getHeight(); } protected boolean operateOriginalSize() { return (this instanceof ImageSplitController) || (this instanceof ImageSampleController); } public double widthRatio() { if (!operateOriginalSize() || imageInformation == null || image == null) { return 1; } double ratio = imageWidth() / imageInformation.getWidth(); return ratio; } public double heightRatio() { if (!operateOriginalSize() || imageInformation == null || image == null) { return 1; } double ratio = imageHeight() / imageInformation.getHeight(); return ratio; } public int operationWidth() { return (int) (imageWidth() / widthRatio()); } public int operationHeight() { return (int) (imageHeight() / heightRatio()); } protected int getRulerStep(double width) { if (width <= 1000) { return 10; } else if (width <= 10000) { return (int) (width / 1000) * 10; } else { return (int) (width / 10000) * 10; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlImageRound.java
released/MyBox/src/main/java/mara/mybox/controller/ControlImageRound.java
package mara.mybox.controller; import java.util.Arrays; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.paint.Color; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.ValidationTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-8-13 * @License Apache License Version 2.0 */ public class ControlImageRound extends BaseController { protected int w, h, wPer, hPer; @FXML protected ComboBox<String> wSelector, hSelector, wPerSelector, hPerSelector; @FXML protected ControlColorSet colorController; @FXML protected RadioButton wPerRadio, hPerRadio; @FXML protected ToggleGroup wGroup, hGroup; @Override public void initControls() { try { super.initControls(); colorController.init(this, baseName + "Color", Color.TRANSPARENT); w = UserConfig.getInt(baseName + "Width", 20); if (w <= 0) { w = 20; } wSelector.getItems().addAll(Arrays.asList("20", "15", "30", "50", "150", "300", "10", "3")); wSelector.setValue(w + ""); wSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkWidth(); } }); wPer = UserConfig.getInt(baseName + "WidthPercent", 10); if (wPer <= 0) { wPer = 10; } wPerSelector.getItems().addAll(Arrays.asList("10", "15", "5", "8", "20", "30", "25")); wPerSelector.setValue(wPer + ""); wPerSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkWidthPercent(); } }); wGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { checkWidthType(); } }); checkWidthType(); h = UserConfig.getInt(baseName + "Height", 20); if (h <= 0) { h = 20; } hSelector.getItems().addAll(Arrays.asList("20", "15", "30", "50", "150", "300", "10", "3")); hSelector.setValue(h + ""); hSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkHeight(); } }); hPer = UserConfig.getInt(baseName + "HeightPercent", 10); if (hPer <= 0) { hPer = 10; } hPerSelector.getItems().addAll(Arrays.asList("10", "15", "5", "8", "20", "30", "25")); hPerSelector.setValue(hPer + ""); hPerSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkHeightPercent(); } }); hGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { checkHeightType(); } }); checkHeightType(); } catch (Exception e) { MyBoxLog.error(e); } } private boolean checkWidthType() { wSelector.setDisable(true); wPerSelector.setDisable(true); wSelector.getEditor().setStyle(null); wPerSelector.getEditor().setStyle(null); if (wPerRadio.isSelected()) { wPerSelector.setDisable(false); return checkWidthPercent(); } else { wSelector.setDisable(false); return checkWidth(); } } private boolean checkWidthPercent() { int v; try { v = Integer.parseInt(wPerSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0 && v <= 100) { wPer = v; UserConfig.setInt(baseName + "WidthPercent", wPer); ValidationTools.setEditorNormal(wPerSelector); return true; } else { popError(message("InvalidParameter") + ": " + message("ImageWidthPercentage")); ValidationTools.setEditorBadStyle(wPerSelector); return false; } } private boolean checkWidth() { int v; try { v = Integer.parseInt(wSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0) { w = v; UserConfig.setInt(baseName + "Width", w); ValidationTools.setEditorNormal(wSelector); return true; } else { popError(message("InvalidParameter") + ": " + message("Width")); ValidationTools.setEditorBadStyle(wSelector); return false; } } private boolean checkHeightType() { hSelector.setDisable(true); hPerSelector.setDisable(true); hSelector.getEditor().setStyle(null); hPerSelector.getEditor().setStyle(null); if (hPerRadio.isSelected()) { hPerSelector.setDisable(false); return checkHeightPercent(); } else { hSelector.setDisable(false); return checkHeight(); } } private boolean checkHeightPercent() { int v; try { v = Integer.parseInt(hPerSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0 && v <= 100) { hPer = v; UserConfig.setInt(baseName + "HeightPercent", hPer); ValidationTools.setEditorNormal(hPerSelector); return true; } else { popError(message("InvalidParameter") + ": " + message("ImageHeightPercentage")); ValidationTools.setEditorBadStyle(hPerSelector); return false; } } private boolean checkHeight() { int v; try { v = Integer.parseInt(hSelector.getValue()); } catch (Exception e) { v = -1; } if (v > 0) { h = v; UserConfig.setInt(baseName + "Height", h); ValidationTools.setEditorNormal(hSelector); return true; } else { popError(message("InvalidParameter") + ": " + message("Height")); ValidationTools.setEditorBadStyle(hSelector); return false; } } public boolean wPercenatge() { return wPerRadio.isSelected(); } public boolean hPercenatge() { return hPerRadio.isSelected(); } public java.awt.Color awtColor() { return colorController.awtColor(); } public Color color() { return colorController.color(); } public boolean pickValues() { return checkWidthType() && checkHeightType(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/TextEditorFormatController.java
released/MyBox/src/main/java/mara/mybox/controller/TextEditorFormatController.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.TextTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2023-7-19 * @License Apache License Version 2.0 */ public class TextEditorFormatController extends BaseChildController { protected TextEditorController fileController; @FXML protected ComboBox<String> charsetSelector; @FXML protected Label bomLabel; public void setParameters(TextEditorController parent) { try { fileController = parent; if (fileController == null || fileController.sourceInformation == null) { close(); return; } baseName = fileController.baseName; setFileType(fileController.TargetFileType); setTitle(message("Format") + " - " + fileController.getTitle()); charsetSelector.getItems().addAll(TextTools.getCharsetNames()); charsetSelector.setValue(fileController.sourceInformation.getCharset().name()); if (fileController.sourceInformation.isWithBom()) { bomLabel.setText(message("WithBom")); } else { bomLabel.setText(""); } } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void okAction() { UserConfig.setString(baseName + "SourceCharset", charsetSelector.getValue()); fileController.refreshAction(); if (closeAfterCheck.isSelected()) { close(); } } /* static methods */ public static TextEditorFormatController open(TextEditorController parent) { try { if (parent == null) { return null; } TextEditorFormatController controller = (TextEditorFormatController) WindowTools.referredTopStage( parent, Fxmls.TextEditorFormatFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlCircle.java
released/MyBox/src/main/java/mara/mybox/controller/ControlCircle.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.TextField; import mara.mybox.data.DoubleCircle; import mara.mybox.dev.MyBoxLog; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-8-13 * @License Apache License Version 2.0 */ public class ControlCircle extends BaseController { protected BaseShapeController shapeController; @FXML protected TextField circleXInput, circleYInput, circleRadiusInput; protected void setParameters(BaseShapeController parent) { try { if (parent == null) { return; } shapeController = parent; } catch (Exception e) { MyBoxLog.error(e); } } public void loadValues() { if (isSettingValues || shapeController.maskCircleData == null) { return; } try { circleXInput.setText(shapeController.scale(shapeController.maskCircleData.getCenterX()) + ""); circleYInput.setText(shapeController.scale(shapeController.maskCircleData.getCenterY()) + ""); circleRadiusInput.setText(shapeController.scale(shapeController.maskCircleData.getRadius()) + ""); } catch (Exception e) { MyBoxLog.error(e); } } public boolean pickValues() { try { float x, y, r; try { x = Float.parseFloat(circleXInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": x"); return false; } try { y = Float.parseFloat(circleYInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": y"); return false; } try { r = Float.parseFloat(circleRadiusInput.getText()); } catch (Exception e) { r = -1f; } if (r <= 0) { popError(message("InvalidParameter") + ": " + message("Radius")); return false; } shapeController.maskCircleData = new DoubleCircle(x, y, r); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/DateInputController.java
released/MyBox/src/main/java/mara/mybox/controller/DateInputController.java
package mara.mybox.controller; import java.util.Date; import javafx.fxml.FXML; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.DateTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-10-2 * @License Apache License Version 2.0 */ public class DateInputController extends BaseInputController { protected ColumnType timeType; @FXML protected TextField timeInput; public DateInputController() { } public void setParameters(BaseController parent, String title, String initValue, ColumnType timeType) { try { super.setParameters(parent, title); this.timeType = timeType; if (initValue != null) { timeInput.setText(initValue); } } catch (Exception e) { MyBoxLog.debug(e); } } public Date getDate() { return DateTools.encodeDate(timeInput.getText()); } @Override public String getInputString() { return timeInput.getText(); } @Override public boolean checkInput() { String s = timeInput.getText(); if (s == null || s.isBlank()) { return true; } if (getDate() == null) { popError(message("InvalidFormat")); return false; } return true; } @FXML public void popTimeExample(MouseEvent mouseEvent) { if (timeType == null) { timeType = ColumnType.Datetime; } switch (timeType) { case Datetime: popMenu = PopTools.popDatetimeExamples(this, popMenu, timeInput, mouseEvent); break; case Date: popMenu = PopTools.popDateExamples(this, popMenu, timeInput, mouseEvent); break; case Era: PopTools.popEraExamples(this, timeInput, mouseEvent); break; } } public static DateInputController open(BaseController parent, String title, String initValue, ColumnType timeType) { try { DateInputController controller = (DateInputController) WindowTools.childStage( parent, Fxmls.DateInputFxml); controller.setParameters(parent, title, initValue, timeType); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlPdfPageAttributes.java
released/MyBox/src/main/java/mara/mybox/controller/ControlPdfPageAttributes.java
package mara.mybox.controller; import java.awt.Color; import java.io.File; import java.util.Arrays; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.util.StringConverter; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.PdfTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.graphics.blend.BlendMode; /** * @Author Mara * @CreateDate 2024-4-24 * @License Apache License Version 2.0 */ public class ControlPdfPageAttributes extends BaseController { protected String waterText, waterImageFile, header, footer, waterTextFontFile, headerFontFile, footerFontFile, numberFontFile; protected boolean setWaterText, setWaterImage, setHeader, setFooter, setNumber; protected int waterTextSize, headerSize, footerSize, numberSize, waterTextMargin, waterTextRotate, waterTextOpacity, waterTextRows, waterTextColumns, waterImageWidth, waterImageHeight, waterImageRotate, waterImageOpacity, waterImageMargin, waterImageRows, waterImageColumns; protected BlendMode waterTextBlend, waterImageBlend; protected Color waterTextColor, headerColor, footerColor, numberColor; @FXML protected CheckBox waterTextCheck, waterImageCheck, headerCheck, footerCheck, numberCheck; @FXML protected ControlTTFSelector waterTextFontController, headerFontController, footerFontController, numberFontController; @FXML protected TextField waterTextInput, waterTextRotateInput, waterTextOpacityInput, waterTextMarginInput, waterTextRowsInput, waterTextColumnsInput, waterImageWidthInput, waterImageHeightInput, waterImageRotateInput, waterImageOpacityInput, waterImageMarginInput, waterImageRowsInput, waterImageColumnsInput, headerInput, footerInput; @FXML protected ComboBox<String> waterTextSizeSelector, headerSizeSelector, footerSizeSelector, numberSizeSelector; @FXML protected ComboBox<BlendMode> waterTextBlendSelector, waterImageBlendSelector; @FXML protected ControlColorSet waterTextColorController, headerColorController, footerColorController, numberColorController; @Override public void setFileType() { setFileType(VisitHistory.FileType.Image); } @Override public void initControls() { try { super.initControls(); List<String> fsize = Arrays.asList( "20", "14", "18", "15", "9", "10", "12", "17", "22", "24", "36", "48", "64", "72", "96"); List<BlendMode> modes = PdfTools.pdfBlendModes(); initWaterText(fsize, modes); initWaterImage(modes); initHeader(fsize); initFooter(fsize); initNumber(fsize); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initWaterText(List<String> fsize, List<BlendMode> modes) { try { setWaterText = UserConfig.getBoolean(baseName + "SetWaterText", true); waterTextCheck.setSelected(setWaterText); waterTextFontController.name(baseName); waterTextSizeSelector.getItems().addAll(fsize); waterTextSize = UserConfig.getInt(baseName + "WaterTextSize", 20); waterTextSizeSelector.setValue(waterTextSize + ""); waterText = UserConfig.getString(baseName + "WaterText", ""); waterTextInput.setText(waterText); waterTextColorController.init(this, baseName + "WaterTextColor", javafx.scene.paint.Color.BLACK); waterTextMargin = UserConfig.getInt(baseName + "WaterTextMargin", 20); waterTextMarginInput.setText(waterTextMargin + ""); waterTextRotate = UserConfig.getInt(baseName + "WaterTextRotate", 45); waterTextRotateInput.setText(waterTextRotate + ""); waterTextOpacity = UserConfig.getInt(baseName + "WaterTextOpacity", 100); waterTextOpacityInput.setText(waterTextOpacity + ""); waterTextBlend = BlendMode.NORMAL; waterTextBlendSelector.getItems().addAll(modes); waterTextBlendSelector.setConverter(new StringConverter<BlendMode>() { @Override public String toString(BlendMode object) { return object.getCOSName().getName(); // return BlendMode.getCOSName(object).getName(); } @Override public BlendMode fromString(String string) { return BlendMode.getInstance(COSName.getPDFName(string)); } }); waterTextBlendSelector.setValue(waterTextBlend); waterTextRows = UserConfig.getInt(baseName + "WaterTextRows", 3); waterTextRowsInput.setText(waterTextRows + ""); waterTextColumns = UserConfig.getInt(baseName + "WaterTextColumns", 3); waterTextColumnsInput.setText(waterTextColumns + ""); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initWaterImage(List<BlendMode> modes) { try { setWaterImage = UserConfig.getBoolean(baseName + "SetWaterImage", true); waterImageCheck.setSelected(setWaterImage); waterImageFile = UserConfig.getString(baseName + "WaterImageFile", null); sourceFileInput.setText(waterImageFile); sourceFileInput.setStyle(null); waterImageWidth = UserConfig.getInt(baseName + "WaterImageWidth", 100); waterImageWidthInput.setText(waterImageWidth + ""); waterImageHeight = UserConfig.getInt(baseName + "WaterImageHeight", 100); waterImageHeightInput.setText(waterImageHeight + ""); waterImageMargin = UserConfig.getInt(baseName + "WaterImageMargin", 20); waterImageMarginInput.setText(waterImageMargin + ""); waterImageRotate = UserConfig.getInt(baseName + "WaterImageRotate", 45); waterImageRotateInput.setText(waterImageRotate + ""); waterImageOpacity = UserConfig.getInt(baseName + "WaterImageOpacity", 100); waterImageOpacityInput.setText(waterImageOpacity + ""); waterImageBlend = BlendMode.NORMAL; waterImageBlendSelector.getItems().addAll(modes); waterImageBlendSelector.setConverter(new StringConverter<BlendMode>() { @Override public String toString(BlendMode object) { return object.getCOSName().getName(); // return BlendMode.getCOSName(object).getName(); } @Override public BlendMode fromString(String string) { return BlendMode.getInstance(COSName.getPDFName(string)); } }); waterImageBlendSelector.setValue(waterImageBlend); waterImageRows = UserConfig.getInt(baseName + "WaterImageRows", 3); waterImageRowsInput.setText(waterImageRows + ""); waterImageColumns = UserConfig.getInt(baseName + "WaterImageColumns", 3); waterImageColumnsInput.setText(waterImageColumns + ""); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initHeader(List<String> fsize) { try { setHeader = UserConfig.getBoolean(baseName + "SetHeader", true); headerCheck.setSelected(setHeader); headerFontController.name(baseName); headerSizeSelector.getItems().addAll(fsize); headerSize = UserConfig.getInt(baseName + "HeaderSize", 20); headerSizeSelector.setValue(headerSize + ""); header = UserConfig.getString(baseName + "Header", ""); headerInput.setText(header); headerColorController.init(this, baseName + "HeaderColor", javafx.scene.paint.Color.BLACK); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initFooter(List<String> fsize) { try { setFooter = UserConfig.getBoolean(baseName + "SetFooter", true); footerCheck.setSelected(setFooter); footerFontController.name(baseName); footerSizeSelector.getItems().addAll(fsize); footerSize = UserConfig.getInt(baseName + "FooterSize", 20); footerSizeSelector.setValue(footerSize + ""); footer = UserConfig.getString(baseName + "Footer", ""); footerInput.setText(footer); footerColorController.init(this, baseName + "FooterColor", javafx.scene.paint.Color.BLACK); } catch (Exception e) { MyBoxLog.error(e, baseName); } } protected void initNumber(List<String> fsize) { try { setNumber = UserConfig.getBoolean(baseName + "SetNumber", true); numberCheck.setSelected(setNumber); numberFontController.name(baseName); numberSizeSelector.getItems().addAll(fsize); numberSize = UserConfig.getInt(baseName + "NumberSize", 20); numberSizeSelector.setValue(numberSize + ""); numberColorController.init(this, baseName + "NumberColor", javafx.scene.paint.Color.BLACK); } catch (Exception e) { MyBoxLog.error(e, baseName); } } public boolean pickWaterText() { try { setWaterText = waterTextCheck.isSelected(); UserConfig.setBoolean(baseName + "SetWaterText", setWaterText); if (!setWaterText) { return true; } String sv = waterTextInput.getText(); if (sv != null && !sv.isBlank()) { waterText = sv.trim(); UserConfig.setString(baseName + "WaterText", waterText); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText")); return false; } int iv; waterTextFontFile = waterTextFontController.ttfFile; if (waterTextFontFile != null && !waterTextFontFile.isBlank()) { try { iv = Integer.parseInt(waterTextSizeSelector.getValue()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterTextSize = iv; UserConfig.setInt(baseName + "WaterTextSize", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("FontSize")); return false; } } try { iv = Integer.parseInt(waterTextMarginInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("Margin")); return false; } waterTextMargin = iv; UserConfig.setInt(baseName + "WaterTextMargin", iv); try { iv = Integer.parseInt(waterTextRotateInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("Rotate")); return false; } waterTextRotate = iv; UserConfig.setInt(baseName + "WaterTextRotate", iv); try { iv = Integer.parseInt(waterTextOpacityInput.getText()); } catch (Exception e) { iv = -1; } if (iv >= 0) { waterTextOpacity = iv; UserConfig.setInt(baseName + "WaterTextOpacity", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("Opacity")); return false; } try { iv = Integer.parseInt(waterTextRowsInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterTextRows = iv; UserConfig.setInt(baseName + "WaterTextRows", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("RowsNumber")); return false; } try { iv = Integer.parseInt(waterTextColumnsInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterTextColumns = iv; UserConfig.setInt(baseName + "WaterTextColumns", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("ColumnsNumber")); return false; } waterTextBlend = waterTextBlendSelector.getValue(); waterTextColor = waterTextColorController.awtColor(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickWaterImage() { try { setWaterImage = waterImageCheck.isSelected(); UserConfig.setBoolean(baseName + "SetWaterImage", setWaterImage); sourceFileInput.setStyle(null); if (!setWaterImage) { return true; } String sv = sourceFileInput.getText(); if (sv != null && !sv.isBlank()) { File file = new File(sv); if (!file.exists() || !file.isFile()) { popError(message("InvalidParameter") + ": " + message("WatermarkImage")); return false; } waterImageFile = file.getAbsolutePath(); UserConfig.setString(baseName + "WaterImageFile", waterImageFile); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage")); return false; } int iv; try { iv = Integer.parseInt(waterImageWidthInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterImageWidth = iv; UserConfig.setInt(baseName + "WaterImageWidth", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Width")); return false; } try { iv = Integer.parseInt(waterImageHeightInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterImageHeight = iv; UserConfig.setInt(baseName + "WaterImageHeight", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Height")); return false; } try { iv = Integer.parseInt(waterImageMarginInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Margin")); return false; } waterImageMargin = iv; UserConfig.setInt(baseName + "WaterImageMargin", iv); try { iv = Integer.parseInt(waterImageRotateInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Rotate")); return false; } waterImageRotate = iv; UserConfig.setInt(baseName + "WaterImageRotate", iv); try { iv = Integer.parseInt(waterImageOpacityInput.getText()); } catch (Exception e) { iv = -1; } if (iv >= 0) { waterImageOpacity = iv; UserConfig.setInt(baseName + "WaterImageOpacity", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("Opacity")); return false; } try { iv = Integer.parseInt(waterImageRowsInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterImageRows = iv; UserConfig.setInt(baseName + "WaterImageRows", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("RowsNumber")); return false; } try { iv = Integer.parseInt(waterImageColumnsInput.getText()); } catch (Exception e) { iv = -1; } if (iv > 0) { waterImageColumns = iv; UserConfig.setInt(baseName + "WaterImageColumns", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkImage") + "-" + message("ColumnsNumber")); return false; } waterImageBlend = waterImageBlendSelector.getValue(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickHeader() { try { setHeader = headerCheck.isSelected(); UserConfig.setBoolean(baseName + "SetHeader", setHeader); if (!setHeader) { return true; } String sv = headerInput.getText(); if (sv != null && !sv.isBlank()) { header = sv.trim(); UserConfig.setString(baseName + "Header", header); } else { popError(message("InvalidParameter") + ": " + message("Header")); return false; } headerFontFile = headerFontController.ttfFile; int iv; if (headerFontFile != null && !headerFontFile.isBlank()) { try { iv = Integer.parseInt(headerSizeSelector.getValue()); } catch (Exception e) { iv = -1; } if (iv > 0) { headerSize = iv; UserConfig.setInt(baseName + "HeaderSize", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("FontSize")); return false; } } headerColor = headerColorController.awtColor(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickFooter() { try { setFooter = footerCheck.isSelected(); UserConfig.setBoolean(baseName + "SetFooter", setFooter); if (!setFooter) { return true; } String sv = footerInput.getText(); if (sv != null && !sv.isBlank()) { footer = sv.trim(); UserConfig.setString(baseName + "Footer", footer); } else { popError(message("InvalidParameter") + ": " + message("Footer")); return false; } footerFontFile = footerFontController.ttfFile; int iv; if (footerFontFile != null && !footerFontFile.isBlank()) { try { iv = Integer.parseInt(footerSizeSelector.getValue()); } catch (Exception e) { iv = -1; } if (iv > 0) { footerSize = iv; UserConfig.setInt(baseName + "FooterSize", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("FontSize")); return false; } } footerColor = footerColorController.awtColor(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickNumber() { try { setNumber = numberCheck.isSelected(); UserConfig.setBoolean(baseName + "SetNumber", setNumber); if (!setNumber) { return true; } numberFontFile = numberFontController.ttfFile; int iv; if (numberFontFile != null && !numberFontFile.isBlank()) { try { iv = Integer.parseInt(numberSizeSelector.getValue()); } catch (Exception e) { iv = -1; } if (iv > 0) { numberSize = iv; UserConfig.setInt(baseName + "NumberSize", iv); } else { popError(message("InvalidParameter") + ": " + message("WatermarkText") + "-" + message("FontSize")); return false; } } numberColor = numberColorController.awtColor(); return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public boolean pickValues() { try { if (!pickWaterText() || !pickWaterImage() || !pickHeader() || !pickFooter() || !pickNumber()) { return false; } if (!setWaterText && !setWaterImage && !setHeader && !setFooter && !setNumber) { popError(message("NothingHandled")); return false; } return true; } catch (Exception e) { MyBoxLog.error(e, baseName); return false; } } public float waterTextWidth(PDFont font) { return PdfTools.fontWidth(font, waterText, waterTextSize); } public float waterTextHeight(PDFont font) { return PdfTools.fontHeight(font, waterTextSize); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlImageSepia.java
released/MyBox/src/main/java/mara/mybox/controller/ControlImageSepia.java
package mara.mybox.controller; import java.util.Arrays; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import mara.mybox.image.data.PixelsOperation; import mara.mybox.image.data.PixelsOperationFactory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.ValidationTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-9-2 * @License Apache License Version 2.0 */ public class ControlImageSepia extends BaseController { protected int intensity; @FXML protected ComboBox<String> intensitySelector; @Override public void initControls() { try { super.initControls(); intensity = UserConfig.getInt(baseName + "Intensity", 60); if (intensity <= 0 || intensity >= 255) { intensity = 60; } intensitySelector.getItems().addAll(Arrays.asList("60", "80", "20", "50", "10", "5", "100", "15", "20")); intensitySelector.setValue(intensity + ""); intensitySelector.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkIntensity(); } }); } catch (Exception e) { MyBoxLog.error(e); } } public boolean checkIntensity() { int v; try { v = Integer.parseInt(intensitySelector.getValue()); } catch (Exception e) { v = -1; } if (v >= 0 && v <= 255) { intensity = v; ValidationTools.setEditorNormal(intensitySelector); return true; } else { popError(message("InvalidParameter") + ": " + message("Intensity")); ValidationTools.setEditorBadStyle(intensitySelector); return false; } } public PixelsOperation pickValues() { if (!checkIntensity()) { return null; } try { PixelsOperation pixelsOperation = PixelsOperationFactory.create( null, null, PixelsOperation.OperationType.Sepia) .setIntPara1(intensity); return pixelsOperation; } catch (Exception e) { displayError(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlSvgNodeEdit.java
released/MyBox/src/main/java/mara/mybox/controller/ControlSvgNodeEdit.java
package mara.mybox.controller; import java.util.List; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.MenuItem; import javafx.scene.control.Tab; import javafx.scene.control.TextArea; import javafx.scene.control.TreeItem; import javafx.scene.layout.FlowPane; import mara.mybox.data.DoubleShape; import mara.mybox.data.XmlTreeNode; import static mara.mybox.data.XmlTreeNode.NodeType.Element; import mara.mybox.db.table.TableStringValues; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.PopTools; import mara.mybox.tools.StringTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * @Author Mara * @CreateDate 2023-6-13 * @License Apache License Version 2.0 */ public class ControlSvgNodeEdit extends ControlXmlNodeEdit { protected SvgEditorController editor; @FXML protected Tab pathTab, styleTab; @FXML protected TextArea styleArea; @FXML protected ControlPath2D pathController; @FXML protected FlowPane shapeOpPane; @Override public void editNode(TreeItem<XmlTreeNode> item) { super.editNode(item); if (treeItem != null) { XmlTreeNode currentTreeNode = treeItem.getValue(); if (currentTreeNode != null && currentTreeNode.getType() == Element) { String name = currentTreeNode.getNode().getNodeName(); if (!name.equalsIgnoreCase("svg")) { if (name.equalsIgnoreCase("path")) { tabPane.getTabs().add(0, pathTab); tabPane.getTabs().add(2, styleTab); } else { tabPane.getTabs().add(1, styleTab); } tabPane.getSelectionModel().select(0); refreshStyle(tabPane); } } } Node focusedNode = null; try { focusedNode = treeItem.getValue().getNode(); } catch (Exception e) { } editor.drawSVG(focusedNode); shapeOpPane.setVisible(item != null && item.getValue() != null && item.getValue().isSvgShape()); } @Override public void setAttributes() { if (node == null) { return; } boolean isPath = "path".equalsIgnoreCase(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); String attrName = attr.getNodeName(); String value = attr.getNodeValue(); if (isPath && "d".equalsIgnoreCase(attrName)) { pathController.loadPath(value); continue; } if ("style".equalsIgnoreCase(attrName)) { styleArea.setText(value); continue; } tableData.add(attrs.item(i)); } } } @Override public Node pickValue() { try { if (node == null) { return null; } super.pickValue(); if (node.getNodeType() != Node.ELEMENT_NODE) { return node; } Element element = (Element) node; String style = styleArea.getText(); if (style != null && !style.isBlank()) { style = StringTools.trimBlanks(style); element.setAttribute("style", style); TableStringValues.add("SvgStyleHistories", style); } else { element.removeAttribute("style"); } if ("path".equalsIgnoreCase(node.getNodeName())) { pathController.pickValue(); String path = pathController.getText(); if (path != null && !path.isBlank()) { path = StringTools.trimBlanks(path); element.setAttribute("d", path); } else { element.removeAttribute("d"); } } return node; } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public void clearNode() { super.clearNode(); pathController.loadPath(""); styleArea.clear(); tabPane.getTabs().removeAll(pathTab, styleTab); } /* style */ @FXML public void popExamplesStyleMenu(Event event) { if (UserConfig.getBoolean("SvgStyleExamplesPopWhenMouseHovering", false)) { showExamplesStyleMenu(event); } } @FXML public void showExamplesStyleMenu(Event event) { PopTools.popMappedValues(this, styleArea, "SvgStyleExamples", HelpTools.svgStyleExamples(), event); } @FXML protected void popStyleHistories(Event event) { if (UserConfig.getBoolean("SvgStyleHistoriesPopWhenMouseHovering", false)) { showStyleHistories(event); } } @FXML protected void showStyleHistories(Event event) { PopTools.popSavedValues(this, styleArea, event, "SvgStyleHistories"); } @FXML protected void clearStyle() { styleArea.clear(); } /* shape */ @FXML public void popShapeMenu(Event event) { if (MenuTools.isPopMenu("SvgNodeShape")) { showShapeMenu(event); } } @FXML public void showShapeMenu(Event event) { if (node == null || !(node instanceof Element)) { return; } List<MenuItem> items = DoubleShape.elementMenu(this, (Element) node); if (items == null) { return; } items.add(MenuTools.popCheckMenu("SvgNodeShape")); popEventMenu(event, items); } public void loadPath(String content) { if (content == null || content.isBlank()) { popError(message("NoData")); return; } pathController.loadPath(content); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/GameEliminationController.java
released/MyBox/src/main/java/mara/mybox/controller/GameEliminationController.java
package mara.mybox.controller; import java.io.File; import java.sql.Connection; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javafx.animation.FadeTransition; import javafx.animation.PathTransition; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.RadioButton; import javafx.scene.control.ScrollPane; import javafx.scene.control.SelectionMode; import javafx.scene.control.Tab; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.ToggleButton; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.effect.DropShadow; import javafx.scene.input.MouseEvent; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.LineTo; import javafx.scene.shape.Path; import javafx.stage.Popup; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.Duration; import mara.mybox.data.ImageItem; import mara.mybox.data.IntPoint; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.LocateTools; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.RecentVisitMenu; import mara.mybox.fxml.SoundTools; import mara.mybox.fxml.cell.ListImageItemCell; import mara.mybox.fxml.cell.TableAutoCommitCell; import mara.mybox.fxml.converter.IntegerStringFromatConverter; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.AppVariables; import mara.mybox.value.FileFilters; import mara.mybox.value.InternalImages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-12-30 * @License Apache License Version 2.0 */ public class GameEliminationController extends BaseController { protected int boardSize, chessWidth, minimumAdjacent, totalScore, autoSpeed, flushDuration, eliminateDelay, flushTimes; protected Map<String, VBox> chessBoard; protected List<Integer> countedChesses; protected IntPoint firstClick; protected boolean countScore, isEliminating, autoPlaying, stopped; protected Random random; protected ObservableList<ScoreRuler> scoreRulersData; protected Map<Integer, Integer> scoreRulers; protected Map<Integer, Integer> scoreRecord; protected Date startTime; protected Adjacent lastElimination, lastRandom; protected String currentStyle, focusStyle, defaultStyle, arcStyle, shadowStyle; protected File soundFile; @FXML protected Tab playTab, chessesTab, rulersTab, settingsTab; @FXML protected VBox chessboardPane; @FXML protected Label chessesLabel, scoreLabel, autoLabel, soundFileLabel; @FXML protected ListView<ImageItem> imagesListview; @FXML protected FlowPane countedImagesPane; @FXML protected CheckBox shadowCheck, arcCheck, scoreCheck; @FXML protected ComboBox<String> chessSizeSelector; @FXML protected TableView<ScoreRuler> rulersTable; @FXML protected TableColumn<ScoreRuler, Integer> numberColumn, scoreColumn; @FXML protected RadioButton guaiRadio, benRadio, guaiBenRadio, muteRadio, customizedSoundRadio, deadRenewRadio, deadChanceRadio, deadPromptRadio, speed1Radio, speed2Radio, speed3Radio, speed5Radio, flush0Radio, flush1Radio, flush2Radio, flush3Radio; @FXML protected HBox selectSoundBox; @FXML protected Button helpMeButton; @FXML protected ToggleButton catButton; @FXML protected ScrollPane scrollPane; @FXML protected ControlWebView imageInfoController; @FXML protected ControlColorSet colorSetController; public GameEliminationController() { baseTitle = message("GameElimniation"); TipsLabelKey = "GameEliminationComments"; } @Override public void initControls() { try { super.initControls(); chessBoard = new HashMap(); scoreRulers = new HashMap(); scoreRecord = new HashMap(); scoreRulersData = FXCollections.observableArrayList(); countedChesses = new ArrayList(); random = new Random(); defaultStyle = "-fx-background-color: transparent; -fx-border-style: solid inside;" + "-fx-border-width: 2; -fx-border-radius: 3; -fx-border-color: transparent;"; arcStyle = "-fx-background-color: white; -fx-border-style: solid inside;" + "-fx-border-width: 2; -fx-border-radius: 10;-fx-background-radius: 10; -fx-border-color: transparent;"; shadowStyle = "-fx-background-color: white;-fx-border-style: solid inside;" + "-fx-border-width: 2; -fx-border-radius: 3; -fx-border-color: white;"; focusStyle = "-fx-border-style: solid inside;-fx-border-width: 2;" + "-fx-border-radius: 3;" + "-fx-border-color: blue;"; flushDuration = 200; minimumAdjacent = 3; colorSetController.init(this, baseName + "Color", Color.RED); colorSetController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { String name = "color:" + colorSetController.name(); addImageAddress(name); } }); catButton.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (firstClick != null) { recoverStyle(firstClick.getX(), firstClick.getY()); firstClick = null; } autoPlaying = catButton.isSelected(); if (autoPlaying) { autoLabel.setText(message("Autoplaying")); findAdjacentAndEliminate(); } else { autoLabel.setText(""); } } }); imagesListview.setCellFactory((ListView<ImageItem> param) -> { ListImageItemCell cell = new ListImageItemCell(); return cell; }); imagesListview.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); imagesListview.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ImageItem>() { @Override public void changed(ObservableValue ov, ImageItem oldVal, ImageItem newVal) { viewImage(); } }); imagesListview.getItems().addListener(new ListChangeListener<ImageItem>() { @Override public void onChanged(ListChangeListener.Change<? extends ImageItem> c) { chessesLabel.setText(message("Count") + ": " + imagesListview.getItems().size()); } }); chessWidth = 50; chessSizeSelector.getItems().addAll(Arrays.asList( "50", "40", "60", "30", "80" )); shadowCheck.setSelected(UserConfig.getBoolean("GameEliminationShadow", false)); arcCheck.setSelected(UserConfig.getBoolean("GameEliminationArc", false)); chessSizeSelector.getSelectionModel().select(UserConfig.getString("GameEliminationChessImageSize", "50")); imageInfoController.setParent(this); } catch (Exception e) { MyBoxLog.debug(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(createButton, message("NewGame") + "\nn / Ctrl+n"); NodeStyleTools.setTooltip(helpMeButton, message("HelpMeFindExchange") + "\nh / Ctrl+h"); NodeStyleTools.setTooltip(catButton, message("AutoPlayGame") + "\np / Ctrl+p"); } catch (Exception e) { MyBoxLog.debug(e); } } @Override public boolean afterSceneLoaded() { if (!super.afterSceneLoaded()) { return false; } loadChesses(true); return true; } public void loadChesses(boolean resetGame) { if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private List<ImageItem> items; @Override protected boolean handle() { try { items = new ArrayList<>(); List<ImageItem> predefinedItems = InternalImages.allWithColors(); List<String> addresses = null; String savedNames = UserConfig.getString("GameEliminationChessImages", null); if (savedNames != null) { addresses = Arrays.asList(savedNames.split(",")); } if (addresses != null) { for (String address : addresses) { boolean predefined = false; for (ImageItem item : predefinedItems) { if (address.equals(item.getAddress())) { items.add(item); predefined = true; break; } } if (!predefined) { items.add(new ImageItem(address)); } } } if (items.size() <= minimumAdjacent) { for (ImageItem pitem : predefinedItems) { boolean existed = false; for (ImageItem eitem : items) { if (eitem.getAddress().equals(pitem.getAddress())) { existed = true; break; } } if (!existed) { items.add(pitem); } if (items.size() > minimumAdjacent) { break; } } } return true; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { imagesListview.getItems().setAll(items); if (resetGame) { okChessesAction(); initRulersTab(); initSettingsTab(); } } }; start(task); } protected void initRulersTab() { try { rulersTable.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); rulersTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Object t, Object t1) { if (!isSettingValues) { } } }); rulersTable.setItems(scoreRulersData); numberColumn.setCellValueFactory(new PropertyValueFactory<>("adjacentNumber")); scoreColumn.setCellValueFactory(new PropertyValueFactory<>("score")); scoreColumn.setCellFactory(new Callback<TableColumn<ScoreRuler, Integer>, TableCell<ScoreRuler, Integer>>() { @Override public TableCell<ScoreRuler, Integer> call(TableColumn<ScoreRuler, Integer> param) { TableAutoCommitCell<ScoreRuler, Integer> cell = new TableAutoCommitCell<ScoreRuler, Integer>(new IntegerStringFromatConverter()) { @Override public boolean valid(Integer value) { return value != null && value >= 0; } @Override public boolean setCellValue(Integer value) { try { if (!valid(value) || !isEditingRow()) { cancelEdit(); return false; } ScoreRuler row = scoreRulersData.get(editingRow); if (row == null || value == null || value < 0) { cancelEdit(); return false; } row.score = value; return super.setCellValue(value); } catch (Exception e) { MyBoxLog.debug(e); return false; } } }; return cell; } }); scoreColumn.getStyleClass().add("editable-column"); } catch (Exception e) { MyBoxLog.debug(e); } } protected void initSettingsTab() { try { isSettingValues = true; guaiRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "Guai"); } } }); benRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "Ben"); } } }); guaiBenRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "GuaiBen"); } } }); muteRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "Mute"); } } }); customizedSoundRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } if (newVal) { UserConfig.setString("GameEliminationSound", "Customized"); } } }); String sound = UserConfig.getString("GameEliminationSound", "Guai"); switch (sound) { case "Ben": benRadio.setSelected(true); break; case "GuaiBen": guaiBenRadio.setSelected(true); break; case "Mute": muteRadio.setSelected(true); break; case "Customized": customizedSoundRadio.setSelected(true); break; default: guaiRadio.setSelected(true); break; } deadRenewRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } UserConfig.setString("GameEliminationDead", "Renew"); } }); deadChanceRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } UserConfig.setString("GameEliminationDead", "Chance"); } }); deadPromptRadio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { if (isSettingValues) { return; } UserConfig.setString("GameEliminationDead", "Prompt"); } }); String dead = UserConfig.getString("GameEliminationDead", "Renew"); switch (dead) { case "Chance": deadChanceRadio.setSelected(true); break; case "Prompt": deadPromptRadio.setSelected(true); break; default: deadRenewRadio.setSelected(true); break; } speed1Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { autoSpeed = 1000; UserConfig.setString("GameEliminationAutoSpeed", "1"); } }); speed2Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { autoSpeed = 2000; UserConfig.setString("GameEliminationAutoSpeed", "2"); } }); speed3Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { autoSpeed = 3000; UserConfig.setString("GameEliminationAutoSpeed", "3"); } }); speed5Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { autoSpeed = 5000; UserConfig.setString("GameEliminationAutoSpeed", "5"); } }); autoSpeed = 2000; String speed = UserConfig.getString("GameEliminationAutoSpeed", "2"); switch (speed) { case "1": speed1Radio.setSelected(true); break; case "3": speed3Radio.setSelected(true); break; case "5": speed5Radio.setSelected(true); break; default: speed2Radio.setSelected(true); break; } flush0Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { flushTimes = 0; eliminateDelay = flushDuration * (2 * flushTimes + 1); UserConfig.setString("GameEliminationFlushTime", "0"); } }); flush1Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { flushTimes = 1; eliminateDelay = flushDuration * (2 * flushTimes + 1); UserConfig.setString("GameEliminationFlushTime", "1"); } }); flush2Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { flushTimes = 2; eliminateDelay = flushDuration * (2 * flushTimes + 1); UserConfig.setString("GameEliminationFlushTime", "2"); } }); flush3Radio.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { flushTimes = 3; eliminateDelay = flushDuration * (2 * flushTimes + 1); UserConfig.setString("GameEliminationFlushTime", "3"); } }); flushTimes = 2; eliminateDelay = flushDuration * (2 * flushTimes + 1); String flush = UserConfig.getString("GameEliminationFlushTime", "2"); switch (flush) { case "1": flush1Radio.setSelected(true); break; case "3": flush3Radio.setSelected(true); break; case "0": flush0Radio.setSelected(true); break; default: flush2Radio.setSelected(true); break; } scoreCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldVal, Boolean newVal) { UserConfig.setBoolean("GameEliminationPopScores", scoreCheck.isSelected()); } }); scoreCheck.setSelected(UserConfig.getBoolean("GameEliminationPopScores", true)); selectSoundBox.disableProperty().bind(customizedSoundRadio.selectedProperty().not()); String sfile = UserConfig.getString("GameEliminationSoundFile", null); if (sfile != null) { soundFile = new File(sfile); if (soundFile.exists()) { soundFileLabel.setText(soundFile.getAbsolutePath()); } else { soundFile = null; } } isSettingValues = false; } catch (Exception e) { MyBoxLog.debug(e); } } public void viewImage() { if (isSettingValues) { return; } imageInfoController.clear(); ImageItem selected = imagesListview.getSelectionModel().getSelectedItem(); if (selected == null || selected.isColor()) { return; } File file = selected.getFile(); if (file == null || !file.exists()) { return; } String body = "<Img src='" + file.toURI().toString() + "' width=" + selected.getWidth() + ">\n"; String comments = selected.getComments(); if (comments != null && !comments.isBlank()) { body += "<BR>" + message(comments); } imageInfoController.loadContent(HtmlWriteTools.html(body)); } @Override public void selectSourceFileDo(File file) { if (file == null) { return; } recordFileOpened(file); addImageAddress(file.getAbsolutePath()); } @FXML protected void okChessesAction() { makeChesses(); } @FXML protected void okRulersAction() { if (isSettingValues) { return; } catButton.setSelected(false); try { countedChesses.clear(); String s = ""; for (Node node : countedImagesPane.getChildren()) { CheckBox cbox = (CheckBox) node; if (cbox.isSelected()) { int index = (int) cbox.getUserData(); countedChesses.add(index); ImageItem item = getImageItem(index); if (s.isBlank()) { s += item.getAddress(); } else { s += "," + item.getAddress(); } } } if (countedChesses.isEmpty()) { if (!PopTools.askSure(getTitle(), message("SureNoScore"))) { return; } } UserConfig.setString("GameEliminationCountedImages", s); scoreRulers.clear(); s = ""; for (int i = 0; i < scoreRulersData.size(); ++i) { ScoreRuler r = scoreRulersData.get(i); scoreRulers.put(r.adjacentNumber, r.score); if (!s.isEmpty()) { s += ","; } s += r.adjacentNumber + "," + r.score; } UserConfig.setString("GameElimniationScoreRulers", s); tabPane.getSelectionModel().select(playTab); newGame(true); } catch (Exception e) { MyBoxLog.debug(e); } } public boolean addImageAddress(String address) { if (isSettingValues || address == null) { return false; } for (ImageItem item : imagesListview.getItems()) { if (item.getAddress().equals(address)) { popError(message("AlreadyExisted")); return false; } } ImageItem item = new ImageItem().setAddress(address); imagesListview.getItems().add(0, item); imagesListview.scrollTo(0); return true; } @FXML protected void clearChessesAction() { imagesListview.getItems().clear(); } @FXML protected void deleteChessesAction() { List<ImageItem> selected = imagesListview.getSelectionModel().getSelectedItems(); if (selected == null || selected.isEmpty()) { popError(message("SelectToHandle")); return; } imagesListview.getItems().removeAll(selected); } @FXML protected void recoverChessesAction() { loadChesses(false); } @FXML protected void chessExamples() { ImageExampleSelectController controller = ImageExampleSelectController.open(this, true); controller.notify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { List<ImageItem> items = controller.selectedItems(); if (items == null || items.isEmpty()) { controller.popError(message("SelectToHandle")); return; } controller.close(); for (ImageItem item : items) { String address = item.getAddress(); for (ImageItem litem : imagesListview.getItems()) { if (litem.getAddress().equals(address)) { address = null; break; } } if (address != null) { imagesListview.getItems().add(0, item); } } imagesListview.scrollTo(0); } }); } @FXML protected void clearCountedImagesAction() { if (isSettingValues) { return; } for (Node node : countedImagesPane.getChildren()) { CheckBox cbox = (CheckBox) node; cbox.setSelected(false); } } @FXML protected void allCountedImagesAction() { if (isSettingValues) { return; } for (Node node : countedImagesPane.getChildren()) { CheckBox cbox = (CheckBox) node; cbox.setSelected(true); } } @FXML @Override public void createAction() { if (isSettingValues) { return; } catButton.setSelected(false); newGame(true); } @FXML protected void settingsAction() { tabPane.getSelectionModel().select(settingsTab); } @FXML public void helpMeAction() { if (isSettingValues || autoPlaying) { return; } Adjacent adjacent = findValidExchange(); if (adjacent != null) { flush(adjacent.exchangei1, adjacent.exchangej1); flush(adjacent.exchangei2, adjacent.exchangej2); } else { promptDeadlock(); } } protected void setAutoplay() { catButton.setSelected(!catButton.isSelected()); } @FXML public void selectSoundFile() { try { if (!checkBeforeNextAction()) { return; } File file = mara.mybox.fxml.FxFileTools.selectFile(this, UserConfig.getPath("MusicPath"), FileFilters.Mp3WavExtensionFilter); if (file == null) { return; } selectSoundFile(file); } catch (Exception e) { // MyBoxLog.error(e); } } public void selectSoundFile(File file) { recordFileOpened(file); String suffix = FileNameTools.ext(file.getName()); if (suffix == null || (!"mp3".equals(suffix.toLowerCase()) && !"wav".equals(suffix.toLowerCase()))) { alertError(message("OnlySupportMp3Wav")); return; } soundFile = file; UserConfig.setString("MusicPath", file.getParent()); UserConfig.setString("GameEliminationSoundFile", file.getAbsolutePath()); soundFileLabel.setText(file.getAbsolutePath()); SoundTools.mp3(soundFile); } @FXML public void showSoundFileMenu(Event event) { if (AppVariables.fileRecentNumber <= 0) {
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ChromaticityBaseController.java
released/MyBox/src/main/java/mara/mybox/controller/ChromaticityBaseController.java
package mara.mybox.controller; import java.io.File; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import mara.mybox.color.ChromaticAdaptation; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.data.VisitHistoryTools; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.RecentVisitMenu; import mara.mybox.tools.TextFileTools; import mara.mybox.value.AppVariables; import mara.mybox.value.FileFilters; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-6-2 10:59:16 * @License Apache License Version 2.0 */ public class ChromaticityBaseController extends BaseWebViewController { protected int scale = 8; protected double sourceX, sourceY, sourceZ, targetX, targetY, targetZ; protected ChromaticAdaptation.ChromaticAdaptationAlgorithm algorithm; protected String exportName; @FXML protected TextField scaleInput; @FXML protected ToggleGroup algorithmGroup; public ChromaticityBaseController() { baseTitle = Languages.message("Chromaticity"); exportName = "ChromaticityData"; } @Override public void setFileType() { setFileType(VisitHistory.FileType.Text); } @Override public void initControls() { try { super.initControls(); initOptions(); } catch (Exception e) { } } public void initOptions() { if (algorithmGroup != null) { algorithmGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkAlgorithm(); } }); checkAlgorithm(); } if (scaleInput != null) { scaleInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { checkScale(); } }); int p = UserConfig.getInt("MatrixDecimalScale", 8); scaleInput.setText(p + ""); } } public void checkAlgorithm() { try { RadioButton selected = (RadioButton) algorithmGroup.getSelectedToggle(); switch (selected.getText()) { case "Bradford": algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.Bradford; break; case "XYZ Scaling": algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.XYZScaling; break; case "Von Kries": algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.VonKries; break; default: algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.Bradford; } } catch (Exception e) { algorithm = ChromaticAdaptation.ChromaticAdaptationAlgorithm.Bradford; } } public void checkScale() { try { int p = Integer.parseInt(scaleInput.getText()); if (p < 0) { scaleInput.setStyle(UserConfig.badStyle()); } else { scale = p; scaleInput.setStyle(null); UserConfig.setInt("MatrixDecimalScale", scale); } } catch (Exception e) { scaleInput.setStyle(UserConfig.badStyle()); } } @FXML public void aboutColor() { openHtml(HelpTools.aboutColor()); } public void showExportPathMenu(Event event) { if (AppVariables.fileRecentNumber <= 0) { return; } new RecentVisitMenu(this, event, true) { @Override public List<VisitHistory> recentPaths() { return VisitHistoryTools.getRecentPathWrite(VisitHistory.FileType.Text); } @Override public void handleSelect() { exportAction(); } @Override public void handlePath(String fname) { handleTargetPath(fname); } }.pop(); } @FXML public void pickExportPath(Event event) { if (MenuTools.isPopMenu("RecentVisit") || AppVariables.fileRecentNumber <= 0) { exportAction(); } else { showExportPathMenu(event); } } @FXML public void popExportPath(Event event) { if (MenuTools.isPopMenu("RecentVisit")) { showExportPathMenu(event); } } // should rewrite this public String exportTexts() { return ""; } @FXML public void exportAction() { final File file = chooseFile(defaultTargetPath(), exportName, FileFilters.TextExtensionFilter); if (file == null) { return; } if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { if (TextFileTools.writeFile(file, exportTexts()) == null) { return false; } recordFileWritten(file, VisitHistory.FileType.Text); return true; } @Override protected void whenSucceeded() { view(file); popSuccessful(); } }; start(task); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/DevTmpController.java
released/MyBox/src/main/java/mara/mybox/controller/DevTmpController.java
package mara.mybox.controller; import java.io.File; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.TextFileTools; import mara.mybox.value.Fxmls; /** * @Author Mara * @CreateDate 2024-12-3 * @License Apache License Version 2.0 */ public class DevTmpController extends BaseTaskController { @Override public void initControls() { try { super.initControls(); // refineFxmls(); // refineFxmls2(); } catch (Exception e) { MyBoxLog.error(e); } } public void refineFxmls() { task = new FxTask<Void>(this) { private File targetPath; private String name; @Override protected boolean handle() { try { int count = 0; File srcPath = new File("D:\\MyBox\\src\\main\\resources\\fxml\\"); targetPath = new File("D:\\tmp\\1\\"); updateLogs(srcPath.getAbsolutePath()); List<File> fxmls = Arrays.asList(srcPath.listFiles()); String scrollImport = "<?import javafx.scene.control.ScrollPane?>"; String controlImport = "<?import javafx.scene.control.*?>"; String newControlPrefx = "<ScrollPane fitToHeight=\"true\" fitToWidth=\"true\" " + "maxHeight=\"1.7976931348623157E308\" maxWidth=\"1.7976931348623157E308\" " + "pannable=\"true\" xmlns=\"http://javafx.com/javafx/23.0.1\" " + "xmlns:fx=\"http://javafx.com/fxml/1\" "; String newSuffix = "\n </content>\n</ScrollPane>\n"; Charset utf8 = Charset.forName("UTF-8"); for (File fxml : fxmls) { name = fxml.getName(); String texts = TextFileTools.readTexts(this, fxml, utf8); int menuPos = texts.indexOf("<fx:include fx:id=\"mainMenu\" source=\"MainMenu.fxml\""); if (menuPos < 0) { // MyBoxLog.console("No menu: " + fxml); continue; } int startPos = texts.indexOf("<BorderPane fx:id=\"thisPane\""); if (startPos < 0) { startPos = texts.indexOf("<VBox fx:id=\"thisPane\""); if (startPos < 0) { startPos = texts.indexOf("<StackPane fx:id=\"thisPane\""); if (startPos < 0) { MyBoxLog.console(fxml); continue; } } } int nsPos = texts.indexOf("xmlns=", startPos); if (nsPos < 0) { MyBoxLog.console(fxml); continue; } int controlPos = texts.indexOf("fx:controller=", startPos); if (nsPos < 0) { MyBoxLog.console(fxml); continue; } int endPos = texts.indexOf(">", startPos); if (endPos < 0) { MyBoxLog.console(fxml); continue; } String newFxml = texts.substring(0, startPos); if (!texts.contains(scrollImport) && !texts.contains(controlImport)) { newFxml += "\n" + scrollImport + "\n"; // MyBoxLog.console("no import:" + fxml); } newFxml += newControlPrefx + texts.substring(controlPos, endPos) + ">\n <content>\n" + texts.substring(startPos, nsPos) + ">" + texts.substring(endPos + 1) + newSuffix; File file = new File(targetPath + File.separator + name); TextFileTools.writeFile(file, newFxml, utf8); updateLogs(++count + ": " + file); } return true; } catch (Exception e) { error = name + " - " + e.toString(); return false; } } @Override protected void whenSucceeded() { browse(targetPath); } }; start(task); } public void refineFxmls2() { task = new FxTask<Void>(this) { private File targetPath; private String name; @Override protected boolean handle() { try { int count = 0; File srcPath = new File("D:\\MyBox\\src\\main\\resources\\fxml\\"); targetPath = new File("D:\\tmp\\1\\"); updateLogs(srcPath.getAbsolutePath()); List<File> fxmls = Arrays.asList(srcPath.listFiles()); String scrollPrefix = "<ScrollPane fitToHeight=\"true\" fitToWidth=\"true\" " + "maxHeight=\"1.7976931348623157E308\" maxWidth=\"1.7976931348623157E308\" " + "pannable=\"true\" xmlns=\"http://javafx.com/javafx/23.0.1\" " + "xmlns:fx=\"http://javafx.com/fxml/1\" "; Charset utf8 = Charset.forName("UTF-8"); int startPane, endPane, startHeight; boolean isBorderPane; String newFxml; for (File fxml : fxmls) { name = fxml.getName(); String texts = TextFileTools.readTexts(this, fxml, utf8); int scrollStart = texts.indexOf(scrollPrefix); if (scrollStart < 0) { // MyBoxLog.console("No menu: " + fxml); continue; } int scrollEnd = texts.indexOf(">", scrollStart); startPane = texts.indexOf("<BorderPane fx:id=\"thisPane\"", scrollEnd); if (startPane > 0) { isBorderPane = true; } else { startPane = texts.indexOf("<StackPane fx:id=\"thisPane\"", scrollEnd); if (startPane > 0) { isBorderPane = false; } else { MyBoxLog.console(fxml); continue; } } endPane = texts.indexOf(">", startPane); startHeight = texts.indexOf("prefHeight=", startPane, endPane); newFxml = texts.substring(0, startPane); if (startHeight > 0) { newFxml = newFxml.replaceFirst("ScrollPane fitToHeight", "ScrollPane " + texts.substring(startHeight, endPane) + " fitToHeight"); } newFxml += isBorderPane ? "<BorderPane" : "<StackPane"; newFxml += " fx:id=\"thisPane\" maxHeight=\"1.7976931348623157E308\" maxWidth=\"1.7976931348623157E308\"" + texts.substring(endPane); File file = new File(targetPath + File.separator + name); TextFileTools.writeFile(file, newFxml, utf8); updateLogs(++count + ": " + file); } return true; } catch (Exception e) { error = name + " - " + e.toString(); return false; } } @Override protected void whenSucceeded() { browse(targetPath); } }; start(task); } /* static */ public static DevTmpController open() { try { DevTmpController controller = (DevTmpController) WindowTools.openStage(Fxmls.DevTmpFxml); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlDataRowExpression.java
released/MyBox/src/main/java/mara/mybox/controller/ControlDataRowExpression.java
package mara.mybox.controller; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.TextArea; import javafx.scene.input.MouseEvent; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.table.TableNodeRowExpression; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.PopTools; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-10-15 * @License Apache License Version 2.0 */ public class ControlDataRowExpression extends BaseDataValuesController { @FXML protected TextArea scriptInput; @FXML protected CheckBox wrapCheck; @Override public void setFileType() { setFileType(VisitHistory.FileType.Javascript); } @Override public void initControls() { try { baseName = "DataRowExpression"; valueInput = scriptInput; valueWrapCheck = wrapCheck; valueName = "script"; super.initControls(); } catch (Exception e) { MyBoxLog.error(e); } } public void edit(String script) { if (!checkBeforeNextAction()) { return; } isSettingValues = true; scriptInput.setText(script); isSettingValues = false; valueChanged(true); } @FXML public void scriptAction() { DataSelectJavaScriptController.open(this, scriptInput); } @FXML protected void popExamples(MouseEvent mouseEvent) { if (UserConfig.getBoolean(baseName + "ExamplesPopWhenMouseHovering", false)) { showExamples(mouseEvent); } } @FXML protected void showExamples(Event event) { PopTools.popJavaScriptExamples(this, event, scriptInput, baseName + "Examples", null); } @FXML public void popHelps(Event event) { if (UserConfig.getBoolean("RowExpressionsHelpsPopWhenMouseHovering", false)) { showHelps(event); } } @FXML public void showHelps(Event event) { popEventMenu(event, HelpTools.rowExpressionHelps()); } /* static */ public static DataTreeNodeEditorController open(BaseController parent, String script) { try { DataTreeNodeEditorController controller = DataTreeNodeEditorController.openTable(parent, new TableNodeRowExpression()); ((ControlDataRowExpression) controller.valuesController).edit(script); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BaseLogsController.java
released/MyBox/src/main/java/mara/mybox/controller/BaseLogsController.java
package mara.mybox.controller; import java.util.Date; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.DateTools; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2022-11-4 * @License Apache License Version 2.0 */ public class BaseLogsController extends BaseController { protected long logsMaxChars, logsTotalLines, logsTotalchars, logsNewlines; protected StringBuffer newLogs; protected long lastLogTime; protected final Object lock = new Object(); @FXML protected TextArea logsTextArea; @FXML protected TextField maxCharsinput; @FXML protected CheckBox verboseCheck; @FXML protected BaseLogsController logsController; @Override public void initValues() { try { super.initValues(); if (logsController != null) { if (logsTextArea == null) { logsTextArea = logsController.logsTextArea; } if (maxCharsinput == null) { maxCharsinput = logsController.maxCharsinput; } if (verboseCheck == null) { verboseCheck = logsController.verboseCheck; } } } catch (Exception e) { MyBoxLog.debug(e); } } @Override public void initControls() { try { super.initControls(); logsMaxChars = UserConfig.getLong("TaskMaxLinesNumber", 5000); if (logsMaxChars <= 0) { logsMaxChars = 5000; } if (maxCharsinput != null) { maxCharsinput.setText(logsMaxChars + ""); maxCharsinput.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { try { if (nv) { return; } long iv = Long.parseLong(maxCharsinput.getText()); if (iv > 0) { logsMaxChars = iv; maxCharsinput.setStyle(null); UserConfig.setLong("TaskMaxLinesNumber", logsMaxChars); } else { maxCharsinput.setStyle(UserConfig.badStyle()); } } catch (Exception e) { maxCharsinput.setStyle(UserConfig.badStyle()); } } }); } if (verboseCheck != null) { verboseCheck.setSelected(UserConfig.getBoolean(interfaceName + "LogVerbose", true)); verboseCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue v, Boolean ov, Boolean nv) { UserConfig.setBoolean(interfaceName + "LogVerbose", verboseCheck.isSelected()); } }); } clearLogs(); } catch (Exception e) { MyBoxLog.debug(e); } } public boolean isLogsVerbose() { return verboseCheck != null ? verboseCheck.isSelected() : false; } @FXML public void clearLogs() { if (logsTextArea == null) { return; } try { synchronized (lock) { newLogs = new StringBuffer(); logsNewlines = 0; logsTotalLines = 0; logsTotalchars = 0; lastLogTime = new Date().getTime(); logsTextArea.setText(""); } } catch (Exception e) { MyBoxLog.debug(e); } } public void initLogs() { if (logsTextArea == null) { return; } if (logsTotalchars > 0) { updateLogs("\n", false, true); } else { clearLogs(); } } public void showLogs(String line) { updateLogs(line, true, true); } public void updateLogs(String line) { updateLogs(line, true, false); } protected void updateLogs(String line, boolean immediate) { updateLogs(line, true, immediate); } public void updateLogs(String line, boolean showTime, boolean immediate) { if (line == null) { return; } if (Platform.isFxApplicationThread()) { handleLogs(line, showTime, immediate); } else { Platform.runLater(() -> { handleLogs(line, showTime, immediate); }); } } protected void handleLogs(String line, boolean showTime, boolean immediate) { if (line == null) { return; } if (logsTextArea == null) { popInformation(line); } else { writeLogs(line, showTime, immediate); } } public void writeLogs(String line, boolean showTime, boolean immediate) { try { synchronized (lock) { if (newLogs == null) { newLogs = new StringBuffer(); } if (showTime) { newLogs.append(DateTools.datetimeToString(new Date())).append(" "); } newLogs.append(line).append("\n"); logsNewlines++; long ctime = new Date().getTime(); if (immediate || logsNewlines > 50 || ctime - lastLogTime > 3000) { String s = newLogs.toString(); logsTotalchars += s.length(); logsTextArea.appendText(s); newLogs = new StringBuffer(); logsTotalLines += logsNewlines; logsNewlines = 0; lastLogTime = ctime; int extra = (int) (logsTotalchars - logsMaxChars); if (extra > 0) { logsTextArea.deleteText(0, extra); logsTotalchars = logsMaxChars; } logsTextArea.selectEnd(); logsTextArea.deselect(); } } } catch (Exception e) { MyBoxLog.debug(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/DataTreeImportController.java
released/MyBox/src/main/java/mara/mybox/controller/DataTreeImportController.java
package mara.mybox.controller; import java.io.File; import java.sql.Connection; import java.util.List; import java.util.Stack; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.data.DataNode; import mara.mybox.db.data.DataNodeTag; import mara.mybox.db.data.DataTag; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.table.BaseNodeTable; import mara.mybox.db.table.TableDataNodeTag; import mara.mybox.db.table.TableDataTag; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.FileTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.xml.sax.Attributes; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * @Author Mara * @CreateDate 2022-3-9 * @License Apache License Version 2.0 */ public class DataTreeImportController extends BaseBatchFileController { protected BaseDataTreeController dataController; protected BaseNodeTable nodeTable; protected String dataName, chainName; protected TableDataNodeTag nodeTagsTable; protected TableDataTag tagTable; protected DataNode parentNode; protected boolean isExample; @FXML protected ToggleGroup existedGroup; @FXML protected RadioButton updateRadio, skipRadio, createRadio; @FXML protected Label parentLabel, formatLabel; @Override public void setFileType() { setFileType(VisitHistory.FileType.XML); } public void setParamters(BaseDataTreeController controller, DataNode node) { try { if (controller == null) { close(); return; } dataController = controller; setData(dataController.nodeTable, node != null ? node : dataController.rootNode, node); } catch (Exception e) { MyBoxLog.error(e); } } public void setData(BaseNodeTable table, DataNode parent, DataNode node) { try { if (table == null) { close(); return; } nodeTable = table; tagTable = new TableDataTag(nodeTable); nodeTagsTable = new TableDataNodeTag(nodeTable); dataName = nodeTable.getTableName(); parentNode = parent; if (parentNode == null) { parentNode = nodeTable.getRoot(); } if (parentNode == null) { close(); return; } baseName = baseName + "_" + dataName; baseTitle = dataName + " - " + message("Import") + " : " + parentNode.getTitle(); chainName = parentNode.shortDescription(); setControls(); } catch (Exception e) { MyBoxLog.error(e); } } public void setControls() { try { setTitle(baseTitle); parentLabel.setText(message("ParentNode") + ": " + chainName); String existed = UserConfig.getString(baseName + "Existed", "Update"); if ("Create".equalsIgnoreCase(existed)) { createRadio.setSelected(true); } else if ("Skip".equalsIgnoreCase(existed)) { skipRadio.setSelected(true); } else { updateRadio.setSelected(true); } existedGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle bv) { if (isSettingValues) { return; } if (createRadio.isSelected()) { UserConfig.setString(baseName + "Existed", "Create"); } else if (skipRadio.isSelected()) { UserConfig.setString(baseName + "Existed", "Skip"); } else { UserConfig.setString(baseName + "Existed", "Update"); } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void importExamples(BaseDataTreeController controller, DataNode node) { setParamters(controller, node); File file = nodeTable.exampleFile(); isSettingValues = true; updateRadio.setSelected(true); isSettingValues = false; isExample = true; startFile(file); } public void importExamples(BaseNodeTable nodeTable, DataNode node, File inFile) { setData(nodeTable, node, node); File file = inFile; if (file == null) { file = nodeTable.exampleFile(); } isSettingValues = true; updateRadio.setSelected(true); miaoCheck.setSelected(false); isSettingValues = false; isExample = true; startFile(file); } @Override public String handleFile(FxTask currentTask, File srcFile, File targetPath) { File validFile = FileTools.removeBOM(currentTask, srcFile); if (validFile == null) { return message("Failed"); } try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(validFile, new DataTreeParser()); return totalItemsHandled > 0 ? message("Successful") : message("Failed"); } catch (Exception e) { return e.toString(); } } class DataTreeParser extends DefaultHandler { protected Connection conn; protected String currentTag; protected StringBuilder value; protected DataNode dataNode; protected DataTag dataTag; protected List<String> columnNames; protected long parentid; protected Stack<Long> parentStack; protected float orderNumber; protected Stack<Float> orderStack; @Override public void startDocument() { try { conn = DerbyBase.getConnection(); conn.setAutoCommit(false); columnNames = nodeTable.dataColumnNames(); totalItemsHandled = 0; parentStack = new Stack<>(); parentid = parentNode.getNodeid(); orderStack = new Stack<>(); orderNumber = 0f; value = new StringBuilder(); showLogs(message("ParentNode") + ": " + chainName); } catch (Exception e) { showLogs(e.toString()); } } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) { try { if (qName == null || qName.isBlank()) { return; } currentTag = qName; switch (currentTag) { case "TreeNode": dataNode = new DataNode(); dataNode.setParentid(parentid).setOrderNumber(++orderNumber); parentStack.push(parentid); orderStack.push(orderNumber); // if (isLogsVerbose()) { // showLogs("New node starting. parentid= " + parentid + ", and it is pushed in stack"); // } break; } value.setLength(0); } catch (Exception e) { showLogs(e.toString()); } } @Override public void characters(char ch[], int start, int length) { try { if (ch == null) { return; } value.append(ch, start, length); } catch (Exception e) { showLogs(e.toString()); } } @Override public void endElement(String uri, String localName, String qName) { try { if (dataNode == null || qName == null || qName.isBlank()) { return; } String s = value.toString().trim(); boolean written = false; switch (qName) { case "title": dataNode.setTitle(s); break; case "NodeTag": if (!s.isBlank()) { dataTag = tagTable.queryTag(conn, s); if (dataTag == null) { dataTag = DataTag.create().setTag(s); dataTag = tagTable.insertData(conn, dataTag); } nodeTagsTable.insertData(conn, new DataNodeTag(dataNode.getNodeid(), dataTag.getTagid())); written = true; } break; case "NodeAttributes": dataNode = saveNode(conn, dataNode); if (isLogsVerbose()) { showLogs("New node saved. parentid=" + dataNode.getParentid() + " nodeid=" + dataNode.getNodeid() + " title=" + dataNode.getTitle()); } parentid = dataNode.getNodeid(); orderNumber = 0f; written = true; // if (isLogsVerbose()) { // showLogs("Now parentid " + parentid); // } break; case "TreeNode": parentid = parentStack.pop(); orderNumber = orderStack.pop(); // if (isLogsVerbose()) { // showLogs("The node ended. " + parentid + " is popped from stack"); // } break; default: if (columnNames.contains(qName)) { dataNode.setValue(qName, nodeTable.importValue(nodeTable.column(qName), s)); // if (isLogsVerbose()) { // showLogs(qName + "=" + s); // } } } if (written && (++totalItemsHandled % Database.BatchSize == 0)) { conn.commit(); } } catch (Exception e) { showLogs(e.toString()); } } public DataNode saveNode(Connection conn, DataNode node) { try { if (createRadio.isSelected()) { return nodeTable.insertData(conn, node); } DataNode existed = nodeTable.find(conn, node.getParentid(), node.getTitle()); if (existed == null) { return nodeTable.insertData(conn, node); } if (skipRadio.isSelected()) { return node; } return nodeTable.updateData(conn, existed); } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public void endDocument() { try { if (conn != null) { conn.commit(); conn.close(); } } catch (Exception e) { showLogs(e.toString()); } } @Override public void warning(SAXParseException e) { showLogs(e.toString()); } @Override public void error(SAXParseException e) { showLogs(e.toString()); } @Override public void fatalError(SAXParseException e) { showLogs(e.toString()); } } @Override public void afterTask(boolean ok) { super.afterTask(ok); if (WindowTools.isRunning(dataController)) { dataController.refreshNode(parentNode, true); if (isExample) { close(); } } } @FXML public void exampleData() { File file = nodeTable.exampleFile(); if (file == null) { file = nodeTable.exampleFile("TextTree"); } XmlEditorController.open(file); } @FXML public void manageAction() { DataTreeController.open(null, false, nodeTable); setIconified(true); } @FXML public void aboutTreeInformation() { openHtml(HelpTools.aboutTreeInformation()); } @Override public boolean needStageVisitHistory() { return false; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BaseDataTreeHandleController.java
released/MyBox/src/main/java/mara/mybox/controller/BaseDataTreeHandleController.java
package mara.mybox.controller; import javafx.fxml.FXML; import mara.mybox.db.table.BaseNodeTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; /** * @Author Mara * @CreateDate 2022-3-14 * @License Apache License Version 2.0 */ public abstract class BaseDataTreeHandleController extends BaseTaskController { protected BaseDataTreeController dataController; protected BaseNodeTable nodeTable; protected String dataName, chainName; public void setParameters(BaseDataTreeController parent) { try { if (parent == null) { close(); return; } dataController = parent; parentController = parent; nodeTable = dataController.nodeTable; dataName = nodeTable.getDataName(); baseName = baseName + "_" + dataName; } catch (Exception e) { MyBoxLog.error(e); } } public boolean dataRunning() { return WindowTools.isRunning(dataController); } public boolean parentRunning() { return WindowTools.isRunning(parentController); } @FXML public void manageAction() { DataTreeController.open(null, false, nodeTable); setIconified(true); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImageRoundBatchController.java
released/MyBox/src/main/java/mara/mybox/controller/ImageRoundBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javafx.fxml.FXML; import mara.mybox.image.tools.BufferedImageTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.ImageDemos; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-9-25 * @License Apache License Version 2.0 */ public class ImageRoundBatchController extends BaseImageEditBatchController { @FXML protected ControlImageRound roundController; public ImageRoundBatchController() { baseTitle = message("ImageBatch") + " - " + message("Round"); } @Override public boolean makeMoreParameters() { return super.makeMoreParameters() && roundController.pickValues(); } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { try { int w, h; if (roundController.wPercenatge()) { w = source.getWidth() * roundController.wPer / 100; } else { w = roundController.w; } if (roundController.hPercenatge()) { h = source.getHeight() * roundController.hPer / 100; } else { h = roundController.h; } BufferedImage target = BufferedImageTools.setRound(currentTask, source, w, h, roundController.awtColor()); return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public void makeDemoFiles(FxTask currentTask, List<String> files, File demoFile, BufferedImage demoImage) { ImageDemos.round(currentTask, files, demoImage, roundController.awtColor(), demoFile); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/PptSplitController.java
released/MyBox/src/main/java/mara/mybox/controller/PptSplitController.java
package mara.mybox.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.text.MessageFormat; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import javafx.beans.binding.Bindings; import javafx.fxml.FXML; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.FileNameTools; import static mara.mybox.value.Languages.message; import org.apache.poi.hslf.usermodel.HSLFShape; import org.apache.poi.hslf.usermodel.HSLFSlide; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFSlide; /** * @Author Mara * @CreateDate 2021-5-20 * @License Apache License Version 2.0 */ public class PptSplitController extends BaseBatchFileController { @FXML protected ControlSplit splitController; public PptSplitController() { baseTitle = message("PptSplit"); } @Override public void setFileType() { setFileType(VisitHistory.FileType.PPTS, VisitHistory.FileType.PPTS); } @Override public void initControls() { try { super.initControls(); splitController.setParameters(this); startButton.disableProperty().unbind(); startButton.disableProperty().bind( Bindings.isEmpty(tableView.getItems()) .or(splitController.valid) ); } catch (Exception e) { MyBoxLog.error(e); } } @Override public String handleFile(FxTask currentTask, File srcFile, File targetPath) { try { int total; try (SlideShow ppt = SlideShowFactory.create(srcFile)) { total = ppt.getSlides().size(); } catch (Exception e) { MyBoxLog.error(e); return e.toString(); } if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } targetFilesCount = 0; targetFiles = new LinkedHashMap<>(); String suffix = FileNameTools.ext(srcFile.getName()); switch (splitController.splitType) { case Size: splitByPagesSize(currentTask, srcFile, targetPath, total, suffix, splitController.size); break; case Number: splitByPagesSize(currentTask, srcFile, targetPath, total, suffix, splitController.size(total, splitController.number)); break; case List: splitByList(currentTask, srcFile, targetPath, suffix); break; default: break; } if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } updateInterface("CompleteFile"); totalItemsHandled += total; return MessageFormat.format(message("HandlePagesGenerateNumber"), totalItemsHandled, targetFilesCount); } catch (Exception e) { MyBoxLog.error(e); return e.toString(); } } protected void splitByPagesSize(FxTask currentTask, File srcFile, File targetPath, int total, String suffix, int pagesSize) { try { int start = 0, end, index = 0; boolean pptx = "pptx".equalsIgnoreCase(suffix); while (start < total) { if (currentTask == null || !currentTask.isWorking()) { return; } end = start + pagesSize; targetFile = makeTargetFile(srcFile, ++index, suffix, targetPath); if (pptx) { if (savePPTX(currentTask, srcFile, targetFile, start, end)) { targetFileGenerated(targetFile); } } else { if (savePPT(currentTask, srcFile, targetFile, start, end)) { targetFileGenerated(targetFile); } } start = end; } } catch (Exception e) { MyBoxLog.error(e); } } protected void splitByList(FxTask currentTask, File srcFile, File targetPath, String suffix) { try { int start = 0, end, index = 0; boolean pptx = "pptx".equalsIgnoreCase(suffix); List<Integer> list = splitController.list; for (int i = 0; i < list.size();) { if (currentTask == null || !currentTask.isWorking()) { return; } // To user, both start and end are 1-based. To codes, both start and end are 0-based. // To user, both start and end are included. To codes, start is included while end is excluded. start = list.get(i++) - 1; end = list.get(i++); targetFile = makeTargetFile(srcFile, ++index, suffix, targetPath); if (pptx) { if (savePPTX(currentTask, srcFile, targetFile, start, end)) { targetFileGenerated(targetFile); } } else { if (savePPT(currentTask, srcFile, targetFile, start, end)) { targetFileGenerated(targetFile); } } } } catch (Exception e) { MyBoxLog.error(e); } } public File makeTargetFile(File srcFile, int index, String ext, File targetPath) { try { String filePrefix = FileNameTools.prefix(srcFile.getName()); String splitPrefix = filePrefix + "_" + index; String splitSuffix = (ext.startsWith(".") ? "" : ".") + ext; File slidePath = targetPath; if (targetSubdirCheck.isSelected()) { slidePath = new File(targetPath, filePrefix); } return makeTargetFile(splitPrefix, splitSuffix, slidePath); } catch (Exception e) { MyBoxLog.error(e); return null; } } // Include start, and exlucde end. Both start and end are 0-based protected boolean savePPT(FxTask currentTask, File srcFile, File targetFile, int start, int end) { try (HSLFSlideShow ppt = new HSLFSlideShow(new FileInputStream(srcFile))) { List<HSLFSlide> slides = ppt.getSlides(); int total = slides.size(); if (start > end || start >= total) { return false; } if (currentTask == null || !currentTask.isWorking()) { return false; } // https://stackoverflow.com/questions/51419421/split-pptx-slideshow-with-apache-poi // Need delete shapes for ppt for (int i = total - 1; i >= end; i--) { if (currentTask == null || !currentTask.isWorking()) { return false; } HSLFSlide slide = slides.get(i); Iterator<HSLFShape> iterator = slide.iterator(); if (iterator != null) { while (iterator.hasNext()) { if (currentTask == null || !currentTask.isWorking()) { return false; } slide.removeShape(iterator.next()); } } ppt.removeSlide(i); } for (int i = 0; i < start; i++) { if (currentTask == null || !currentTask.isWorking()) { return false; } HSLFSlide slide = slides.get(0); Iterator<HSLFShape> iterator = slide.iterator(); if (iterator != null) { while (iterator.hasNext()) { if (currentTask == null || !currentTask.isWorking()) { return false; } slide.removeShape(iterator.next()); } } ppt.removeSlide(0); } if (currentTask == null || !currentTask.isWorking()) { return false; } ppt.write(targetFile); return targetFile.exists(); } catch (Exception e) { MyBoxLog.error(e); return false; } } // Include start, and exlucde end. Both start and end are 0-based protected boolean savePPTX(FxTask currentTask, File srcFile, File targetFile, int start, int end) { try (XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(srcFile)); FileOutputStream out = new FileOutputStream(targetFile)) { List<XSLFSlide> slides = ppt.getSlides(); if (currentTask == null || !currentTask.isWorking()) { return false; } int total = slides.size(); // Looks need not remove shapes for pptx in current version for (int i = total - 1; i >= end; i--) { if (currentTask == null || !currentTask.isWorking()) { return false; } ppt.removeSlide(i); } for (int i = 0; i < start; i++) { if (currentTask == null || !currentTask.isWorking()) { return false; } ppt.removeSlide(0); } if (currentTask == null || !currentTask.isWorking()) { return false; } ppt.write(out); } catch (Exception e) { MyBoxLog.error(e); return false; } return targetFile != null && targetFile.exists(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImageScopeViewsController.java
released/MyBox/src/main/java/mara/mybox/controller/ImageScopeViewsController.java
package mara.mybox.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Tab; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.VBox; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-11-12 * @License Apache License Version 2.0 */ public class ImageScopeViewsController extends BaseChildController { protected ControlImageScope scopeController; @FXML protected ControlImageView selectedController, sourceController, maskController; @FXML protected Tab selectedTab, sourceTab, maskTab; @FXML protected VBox selectedBox, pixelsBox, sourceBox; public ImageScopeViewsController() { baseTitle = message("Scope"); } protected void setParameters(ControlImageScope parent) { try { scopeController = parent; scopeController.showNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { refreshAction(); } }); refreshAction(); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void refreshAction() { refreshSource(); refreshMask(); refreshScope(); } public Image srcImage() { return scopeController.srcImage(); } @FXML public void refreshSource() { Image srcImage = srcImage(); if (srcImage == null) { return; } sourceController.loadImage(srcImage); } @FXML public void refreshMask() { Image srcImage = srcImage(); if (srcImage == null) { return; } maskController.loadImage(scopeController.imageView.getImage()); } @FXML public void refreshScope() { Image srcImage = srcImage(); if (srcImage == null) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private Image selectedScope; @Override protected boolean handle() { try { selectedScope = scopeController.scopeImage(this); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override protected void whenSucceeded() { selectedController.loadImage(selectedScope); } }; start(task, selectedBox); } @Override public boolean handleKeyEvent(KeyEvent event) { Tab tab = tabPane.getSelectionModel().getSelectedItem(); if (tab == sourceTab) { if (sourceController.handleKeyEvent(event)) { return true; } } else if (tab == selectedTab) { if (selectedController.handleKeyEvent(event)) { return true; } } else if (tab == maskTab) { if (maskController.handleKeyEvent(event)) { return true; } } return super.handleKeyEvent(event); } /* static methods */ public static ImageScopeViewsController open(ControlImageScope parent) { try { if (parent == null || !parent.isShowing()) { return null; } ImageScopeViewsController controller = (ImageScopeViewsController) WindowTools.referredTopStage( parent, Fxmls.ImageScopeViewsFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlData2DMultipleLinearRegressionTable.java
released/MyBox/src/main/java/mara/mybox/controller/ControlData2DMultipleLinearRegressionTable.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.fxml.FXML; import mara.mybox.db.data.ColumnDefinition.ColumnType; import mara.mybox.db.data.Data2DColumn; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2022-4-21 * @License Apache License Version 2.0 */ public class ControlData2DMultipleLinearRegressionTable extends ControlData2DSimpleLinearRegressionTable { @Override public List<Data2DColumn> createColumns() { try { List<Data2DColumn> cols = new ArrayList<>(); cols.add(new Data2DColumn(message("DependentVariable"), ColumnType.String, 100)); cols.add(new Data2DColumn(message("IndependentVariable"), ColumnType.String, 200)); cols.add(new Data2DColumn(message("AdjustedRSquared"), ColumnType.Double, 80)); cols.add(new Data2DColumn(message("CoefficientOfDetermination"), ColumnType.Double, 80)); cols.add(new Data2DColumn(message("Coefficients"), ColumnType.Double, 80)); cols.add(new Data2DColumn(message("Intercept"), ColumnType.Double, 100)); return cols; } catch (Exception e) { MyBoxLog.error(e); return null; } } @FXML @Override public void editAction() { if (regressController == null) { return; } List<String> selected = selected(); if (selected == null) { Data2DMultipleLinearRegressionController.open(regressController.dataController); } else { try { Data2DMultipleLinearRegressionController controller = (Data2DMultipleLinearRegressionController) WindowTools .referredStage(regressController.parentController, Fxmls.Data2DMultipleLinearRegressionFxml); controller.categoryColumnSelector.setValue(selected.get(1)); List<Integer> cols = new ArrayList<>(); List<String> names = ((Data2DMultipleLinearRegressionCombinationController) regressController).namesMap.get(selected.get(2)); for (String name : names) { cols.add(regressController.data2D.colOrder(name)); } controller.checkedColsIndices = cols; controller.interceptCheck.setSelected(regressController.interceptCheck.isSelected()); controller.cloneOptions(regressController); controller.setParameters(regressController.dataController); controller.startAction(); controller.requestMouse(); } catch (Exception e) { MyBoxLog.error(e); } } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/Data2DStatisticController.java
released/MyBox/src/main/java/mara/mybox/controller/Data2DStatisticController.java
package mara.mybox.controller; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import mara.mybox.calculation.DescriptiveStatistic; import mara.mybox.calculation.DescriptiveStatistic.StatisticObject; import mara.mybox.calculation.DoubleStatistic; import mara.mybox.data2d.DataTable; import mara.mybox.data2d.TmpTable; import mara.mybox.data2d.tools.Data2DConvertTools; import mara.mybox.data2d.writer.Data2DWriter; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-12-12 * @License Apache License Version 2.0 */ public class Data2DStatisticController extends BaseData2DTaskTargetsController { protected DescriptiveStatistic calculation; protected int categorysCol; protected String selectedCategory; @FXML protected ControlStatisticSelection statisticController; @FXML protected VBox dataOptionsBox; @FXML protected FlowPane categoryColumnsPane; @FXML protected ComboBox<String> categoryColumnSelector; public Data2DStatisticController() { baseTitle = message("DescriptiveStatistics"); } @Override public void initOptions() { try { super.initOptions(); categoryColumnSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkOptions(); } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void dataChanged() { try { super.dataChanged(); List<String> names = data2D.columnNames(); if (names == null || names.isEmpty()) { return; } isSettingValues = true; selectedCategory = categoryColumnSelector.getSelectionModel().getSelectedItem(); names.add(0, message("RowNumber")); categoryColumnSelector.getItems().setAll(names); if (selectedCategory != null && names.contains(selectedCategory)) { categoryColumnSelector.setValue(selectedCategory); } else { categoryColumnSelector.getSelectionModel().select(0); } isSettingValues = false; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void objectChanged() { super.objectChanged(); if (rowsRadio.isSelected()) { if (!dataOptionsBox.getChildren().contains(categoryColumnsPane)) { dataOptionsBox.getChildren().add(1, categoryColumnsPane); } } else { if (dataOptionsBox.getChildren().contains(categoryColumnsPane)) { dataOptionsBox.getChildren().remove(categoryColumnsPane); } } } @Override public boolean checkOptions() { try { if (!super.checkOptions()) { return false; } categorysCol = -1; if (rowsRadio.isSelected()) { selectedCategory = categoryColumnSelector.getSelectionModel().getSelectedItem(); if (selectedCategory != null && categoryColumnSelector.getSelectionModel().getSelectedIndex() != 0) { categorysCol = data2D.colOrder(selectedCategory); } } calculation = statisticController.pickValues() .setScale(scale) .setInvalidAs(invalidAs) .setTaskController(this) .setData2D(data2D) .setColsIndices(checkedColsIndices) .setColsNames(checkedColsNames) .setCategoryName(categorysCol >= 0 ? selectedCategory : null); switch (objectType) { case Rows: calculation.setStatisticObject(StatisticObject.Rows); break; case All: calculation.setStatisticObject(StatisticObject.All); break; default: calculation.setStatisticObject(StatisticObject.Columns); break; } UserConfig.setBoolean(baseName + "SkipNonnumeric", skipInvalidRadio.isSelected()); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override protected void startOperation() { try { if (!calculation.prepare()) { return; } data2D.resetStatistic(); if (isAllPages()) { switch (objectType) { case Rows: handleAllTask(); break; case All: handleAllByAllTask(); break; default: handleAllByColumnsTask(); break; } } else { handleRowsTask(); } } catch (Exception e) { MyBoxLog.debug(e); } } @Override public boolean handleRows() { List<Integer> colsIndices = checkedColsIndices; if (rowsRadio.isSelected() && categorysCol >= 0) { colsIndices.add(0, categorysCol); } if (!calculation.statisticData(sourceController.rowsFiltered(colsIndices, rowsRadio.isSelected() && categorysCol < 0))) { return false; } outputColumns = calculation.getOutputColumns(); outputData = calculation.getOutputData(); return true; } public void handleAllByColumnsTask() { if (task != null) { task.cancel(); } taskSuccessed = false; task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { try { data2D.startTask(this, filterController.filter); calculation.setTask(this); if (calculation.needStored()) { TmpTable tmpTable = TmpTable.toStatisticTable(data2D, this, checkedColsIndices, invalidAs); if (tmpTable == null) { return false; } tmpTable.startTask(this, null); calculation.setData2D(tmpTable) .setColsIndices(tmpTable.columnIndices().subList(1, tmpTable.columnsNumber())) .setColsNames(tmpTable.columnNames().subList(1, tmpTable.columnsNumber())); taskSuccessed = calculation.statisticAllByColumns(); tmpTable.stopFilter(); tmpTable.drop(); } else { taskSuccessed = calculation.statisticAllByColumnsWithoutStored(); } data2D.stopFilter(); return taskSuccessed; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { outputColumns = calculation.getOutputColumns(); outputData = calculation.getOutputData(); if (targetController.inTable()) { updateTable(); } else { outputRowsToExternal(); } } @Override protected void finalAction() { super.finalAction(); calculation.setTask(null); closeTask(ok); } }; start(task, false); } public void handleAllByAllTask() { if (task != null) { task.cancel(); } taskSuccessed = false; task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { try { data2D.startTask(this, filterController.filter); calculation.setTask(this); if (calculation.needStored()) { DataTable dataTable = Data2DConvertTools.singleColumn(this, data2D, checkedColsIndices); if (dataTable == null) { return false; } dataTable.startTask(this, null); calculation.setTask(this); calculation.setData2D(dataTable) .setColsIndices(dataTable.columnIndices().subList(1, 2)) .setColsNames(dataTable.columnNames().subList(1, 2)); taskSuccessed = calculation.statisticAllByColumns(); } else { DoubleStatistic statisticData = data2D.statisticByAllWithoutStored(checkedColsIndices, calculation); if (statisticData == null) { return false; } calculation.statisticByColumnsWrite(statisticData); taskSuccessed = true; } data2D.stopFilter(); return taskSuccessed; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { outputColumns = calculation.getOutputColumns(); outputData = calculation.getOutputData(); if (targetController.inTable()) { updateTable(); } else { outputRowsToExternal(); } } @Override protected void finalAction() { super.finalAction(); calculation.setTask(null); closeTask(ok); } }; start(task, false); } @Override public boolean handleAllData(FxTask currentTask, Data2DWriter writer) { List<Integer> colsIndices = checkedColsIndices; if (rowsRadio.isSelected() && categorysCol >= 0) { colsIndices.add(0, categorysCol); } return data2D.statisticByRows(currentTask, writer, calculation.getOutputNames(), colsIndices, calculation); } /* static */ public static Data2DStatisticController open(BaseData2DLoadController tableController) { try { Data2DStatisticController controller = (Data2DStatisticController) WindowTools.referredStage( tableController, Fxmls.Data2DStatisticFxml); controller.setParameters(tableController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImageConvolutionBatchController.java
released/MyBox/src/main/java/mara/mybox/controller/ImageConvolutionBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import javafx.fxml.FXML; import mara.mybox.image.data.ImageConvolution; import mara.mybox.db.data.ConvolutionKernel; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-9-23 * @License Apache License Version 2.0 */ public class ImageConvolutionBatchController extends BaseImageEditBatchController { protected ConvolutionKernel kernel; @FXML protected ControlImageConvolution convolutionController; public ImageConvolutionBatchController() { baseTitle = message("ImageBatch") + " - " + message("Convolution"); } @Override public boolean makeMoreParameters() { if (!super.makeMoreParameters()) { return false; } kernel = convolutionController.pickValues(); return kernel != null; } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { try { ImageConvolution convolution = ImageConvolution.create(); convolution.setImage(source).setKernel(kernel).setTask(currentTask); return convolution.start(); } catch (Exception e) { displayError(e.toString()); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/SvgPathController.java
released/MyBox/src/main/java/mara/mybox/controller/SvgPathController.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.TreeItem; import mara.mybox.data.DoublePath; import mara.mybox.data.XmlTreeNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import org.w3c.dom.Element; /** * @Author Mara * @CreateDate 2024-1-2 * @License Apache License Version 2.0 */ public class SvgPathController extends BaseSvgShapeController { protected DoublePath initData; @FXML protected ControlPath2D pathController; @Override public void initMore() { try { shapeName = message("SVGPath"); anchorCheck.setSelected(true); showAnchors = true; popShapeMenu = true; } catch (Exception e) { MyBoxLog.error(e); } } public void setInitData(DoublePath initData) { this.initData = initData; } @Override public boolean afterImageLoaded() { try { if (!super.afterImageLoaded()) { return false; } if (initData != null) { loadSvgPath(initData); initData = null; } return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public boolean elementToShape(Element node) { try { String d = node.getAttribute("d"); maskPathData = new DoublePath(this, d); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @Override public void showShape() { showMaskPath(); } @Override public void setShapeInputs() { if (maskPathData != null) { pathController.loadPath(maskPathData.getContent()); } else { pathController.loadPath(null); } } @Override public boolean shape2Element() { try { if (maskPathData == null) { return false; } if (shapeElement == null) { shapeElement = doc.createElement("path"); } shapeElement.setAttribute("d", maskPathData.getContent()); return true; } catch (Exception e) { MyBoxLog.error(e); } return false; } @Override public boolean pickShape() { try { if (!pathController.pickValue()) { return false; } maskPathData.setContent(pathController.getText()); maskPathData.setSegments(pathController.getSegments()); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @FXML @Override public boolean withdrawAction() { if (imageView == null || imageView.getImage() == null) { return false; } pathController.removeLastItem(); goShape(); return true; } @FXML @Override public void clearAction() { if (imageView == null || imageView.getImage() == null) { return; } pathController.clear(); goShape(); } /* static */ public static SvgPathController drawShape(SvgEditorController editor, TreeItem<XmlTreeNode> item, Element element) { try { if (editor == null || item == null) { return null; } SvgPathController controller = (SvgPathController) WindowTools.childStage( editor, Fxmls.SvgPathFxml); controller.setParameters(editor, item, element); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static SvgPathController loadPath(SvgEditorController editor, TreeItem<XmlTreeNode> item, DoublePath pathData) { try { if (editor == null || item == null) { return null; } SvgPathController controller = (SvgPathController) WindowTools.childStage( editor, Fxmls.SvgPathFxml); controller.setInitData(pathData); controller.setParameters(editor, item, null); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/MyBoxLanguagesController.java
released/MyBox/src/main/java/mara/mybox/controller/MyBoxLanguagesController.java
package mara.mybox.controller; import java.io.File; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.MenuItem; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; import javafx.stage.Stage; import javafx.util.Callback; import javafx.util.converter.DefaultStringConverter; import mara.mybox.controller.MyBoxLanguagesController.LanguageItem; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.cell.TableAutoCommitCell; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.ConfigTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.value.AppVariables; import static mara.mybox.value.AppVariables.useChineseWhenBlankTranslation; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-12-27 * @License Apache License Version 2.0 */ public class MyBoxLanguagesController extends BaseTableViewController<LanguageItem> { protected String langName; protected boolean changed; @FXML protected ListView<String> listView; @FXML protected TableColumn<LanguageItem, String> keyColumn, englishColumn, chineseColumn, valueColumn; @FXML protected Label langLabel; @FXML protected Button addLangButton, useLangButton, deleteLangButton, editLangButton; @FXML protected CheckBox chineseCheck; public MyBoxLanguagesController() { baseTitle = message("ManageLanguages"); TipsLabelKey = "MyBoxLanguagesTips"; } @Override public void initControls() { try { super.initControls(); chineseCheck.selectedProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Object t, Object t1) { useChineseWhenBlankTranslation = chineseCheck.isSelected(); UserConfig.setBoolean("UseChineseWhenBlankTranslation", useChineseWhenBlankTranslation); } }); chineseCheck.setSelected(useChineseWhenBlankTranslation); listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Object t, Object t1) { checkListSelected(); } }); listView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.getClickCount() > 1) { editLang(); } } }); refreshLang(); checkListSelected(); changed = false; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(useLangButton, new Tooltip(message("SetAsInterfaceLanguage"))); NodeStyleTools.setTooltip(editLangButton, new Tooltip(message("Edit") + "\n" + message("DoubleClick"))); NodeStyleTools.setTooltip(chineseCheck, new Tooltip(message("BlankAsChinese"))); } catch (Exception e) { MyBoxLog.error(e); } } /* Languages List */ @FXML public void refreshLang() { try { isSettingValues = true; listView.getItems().clear(); listView.getItems().addAll(Languages.userLanguages()); isSettingValues = false; } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void addLang() { if (changed) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle(getTitle()); alert.setHeaderText(getTitle()); alert.setContentText(Languages.message("NeedSaveBeforeAction")); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); ButtonType buttonSave = new ButtonType(Languages.message("Save")); ButtonType buttonNotSave = new ButtonType(Languages.message("NotSave")); ButtonType buttonCancel = new ButtonType(Languages.message("Cancel")); alert.getButtonTypes().setAll(buttonSave, buttonNotSave, buttonCancel); Stage stage = (Stage) alert.getDialogPane().getScene().getWindow(); stage.setAlwaysOnTop(true); stage.toFront(); Optional<ButtonType> result = alert.showAndWait(); if (result == null || !result.isPresent()) { return; } if (result.get() == buttonSave) { saveAction(); return; } else if (result.get() == buttonCancel) { return; } } String name = PopTools.askValue(getTitle(), message("InputLanguageComments"), message("InputLanguageName"), null); if (name == null || name.isBlank()) { return; } if ("en".equalsIgnoreCase(name) || "zh".equalsIgnoreCase(name) || name.startsWith("en_") || name.startsWith("zh_")) { popError(message("InputLanguageComments")); return; } langName = name.trim(); langLabel.setText(langName); loadLanguage(null); } @FXML public void editLang() { String selected = listView.getSelectionModel().getSelectedItem(); if (selected == null) { popError(message("SelectToHandle")); return; } langName = selected; loadLanguage(selected); } @FXML public void deleteLang() { List<String> selected = listView.getSelectionModel().getSelectedItems(); if (selected == null || selected.isEmpty()) { popError(message("SelectToHandle")); return; } if (!PopTools.askSure(getTitle(), Languages.message("SureDelete"))) { return; } String currentLang = Languages.getLangName(); for (String name : selected) { File interfaceFile = Languages.interfaceLanguageFile(name); FileDeleteTools.delete(interfaceFile); if (name.equals(currentLang)) { UserConfig.deleteValue("language"); } } isSettingValues = true; listView.getItems().removeAll(selected); langName = null; langLabel.setText(""); tableData.clear(); isSettingValues = false; checkListSelected(); Languages.refreshBundle(); popSuccessful(); } @FXML public void useLang() { String selected = listView.getSelectionModel().getSelectedItem(); if (selected == null) { popError(message("SelectToHandle")); return; } Languages.setLanguage(selected); WindowTools.reloadAll(); } protected void checkListSelected() { if (isSettingValues) { return; } String selected = listView.getSelectionModel().getSelectedItem(); if (selected == null) { deleteLangButton.setDisable(true); editLangButton.setDisable(true); useLangButton.setDisable(true); } else { deleteLangButton.setDisable(false); editLangButton.setDisable(false); useLangButton.setDisable(false); } } @FXML public void openPath() { browseURI(AppVariables.MyBoxLanguagesPath.toURI()); } /* Language Items */ @Override public void initColumns() { try { keyColumn.setCellValueFactory(new PropertyValueFactory<>("key")); englishColumn.setCellValueFactory(new PropertyValueFactory<>("english")); chineseColumn.setCellValueFactory(new PropertyValueFactory<>("chinese")); valueColumn.setCellValueFactory(new PropertyValueFactory<>("value")); valueColumn.setCellFactory(new Callback<TableColumn<LanguageItem, String>, TableCell<LanguageItem, String>>() { @Override public TableCell<LanguageItem, String> call(TableColumn<LanguageItem, String> param) { return new LanguageCell(); } }); valueColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<LanguageItem, String>>() { @Override public void handle(TableColumn.CellEditEvent<LanguageItem, String> t) { if (t == null) { return; } LanguageItem row = t.getRowValue(); if (row == null) { return; } String v = t.getNewValue(); String o = row.getValue(); if (v == null && o == null || v != null && v.equals(o)) { return; } row.setValue(v); tableChanged(true); } }); valueColumn.setEditable(true); valueColumn.getStyleClass().add("editable-column"); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void tableChanged(boolean changed) { if (isSettingValues) { return; } this.changed = changed; updateStatus(); } @Override public void updateStatus() { setTitle(baseTitle + " - " + langName + (changed ? "*" : "")); langLabel.setText(langName + (changed ? "*" : "")); boolean isEmpty = tableData == null || tableData.isEmpty(); boolean none = isNoneSelected(); copyItemsButton.setDisable(none); saveButton.setDisable(isEmpty); chineseCheck.setDisable(isEmpty); lostFocusCommitCheck.setDisable(isEmpty); } public void loadLanguage(String name) { if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private List<LanguageItem> items; @Override protected boolean handle() { try { error = null; Map<String, String> interfaceItems = null; File interfaceFile = Languages.interfaceLanguageFile(name); if (interfaceFile != null && interfaceFile.exists()) { interfaceItems = ConfigTools.readValues(interfaceFile); } Enumeration<String> interfaceKeys = Languages.BundleEn.getKeys(); items = new ArrayList<>(); while (interfaceKeys.hasMoreElements()) { String key = interfaceKeys.nextElement(); LanguageItem item = new LanguageItem(key, Languages.BundleEn.getString(key), Languages.BundleZhCN.getString(key)); if (interfaceItems != null) { item.setValue(interfaceItems.get(key)); } items.add(item); } } catch (Exception e) { error = e.toString(); } return true; } @Override protected void whenSucceeded() { if (error == null) { isSettingValues = true; tableData.setAll(items); isSettingValues = false; tableChanged(name == null); } else { popError(error); } } }; start(task); } @FXML public void copyEnglish() { List<LanguageItem> selected = tableView.getSelectionModel().getSelectedItems(); if (selected == null || selected.isEmpty()) { return; } for (LanguageItem item : selected) { item.setValue(item.getEnglish()); } tableView.refresh(); } @FXML public void copyChinese() { List<LanguageItem> selected = tableView.getSelectionModel().getSelectedItems(); if (selected == null || selected.isEmpty()) { return; } for (LanguageItem item : selected) { item.setValue(item.getChinese()); } tableView.refresh(); } @FXML @Override public void saveAction() { if (langName == null) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { try { error = null; Map<String, String> interfaceItems = new HashMap(); File interfaceFile = Languages.interfaceLanguageFile(langName); for (LanguageItem item : tableView.getItems()) { String value = item.getValue(); if (value != null && !value.isBlank()) { interfaceItems.put(item.getKey(), value); } } ConfigTools.writeValues(interfaceFile, interfaceItems); } catch (Exception e) { error = e.toString(); } return true; } @Override protected void whenSucceeded() { if (error == null) { if (!listView.getItems().contains(langName)) { listView.getItems().add(0, langName); } tableChanged(false); popSuccessful(); if (langName.equals(Languages.getLangName())) { WindowTools.reloadAll(); } } else { popError(error); } } }; start(task); } @Override public boolean controlAltE() { copyEnglish(); return true; } @FXML public void popCopyMenu(MouseEvent event) { popTableMenu(event); } @Override protected List<MenuItem> makeTableContextMenu() { List<MenuItem> items = new ArrayList<>(); MenuItem menu; menu = new MenuItem(Languages.message("CopyEnglish")); menu.setOnAction((ActionEvent menuItemEvent) -> { copyEnglish(); }); items.add(menu); menu = new MenuItem(Languages.message("CopyChinese")); menu.setOnAction((ActionEvent menuItemEvent) -> { copyChinese(); }); items.add(menu); return items; } public class LanguageCell extends TableAutoCommitCell { public LanguageCell() { super(new DefaultStringConverter()); } protected void setCellValue(int rowIndex, String value) { if (isSettingValues || rowIndex < 0 || rowIndex >= tableData.size()) { return; } LanguageItem item = tableData.get(rowIndex); String currentValue = item.getValue(); if ((currentValue == null && value == null) || (currentValue != null && currentValue.equals(value))) { return; } item.setValue(value); tableData.set(rowIndex, item); } @Override public void editCell() { LanguageItem item = tableData.get(editingRow); String en = item.getEnglish(); String value = item.getValue(); if (value != null && value.contains("\n") || en != null && en.contains("\n")) { MyBoxLanguageInputController inputController = MyBoxLanguageInputController.open((MyBoxLanguagesController) myController, item); inputController.getNotify().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { String value = inputController.getInput(); setCellValue(editingRow, value); inputController.close(); } }); } else { super.editCell(); } } } public class LanguageItem { protected String key, english, chinese, value; public LanguageItem(String key, String english, String chinese) { this.key = key; this.english = english; this.chinese = chinese; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getEnglish() { return english; } public void setEnglish(String english) { this.english = english; } public String getChinese() { return chinese; } public void setChinese(String chinese) { this.chinese = chinese; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/HtmlToPdfController.java
released/MyBox/src/main/java/mara/mybox/controller/HtmlToPdfController.java
package mara.mybox.controller; import java.io.File; import javafx.fxml.FXML; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.TextFileTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-10-17 * @License Apache License Version 2.0 */ public class HtmlToPdfController extends BaseBatchFileController { @FXML protected ControlHtml2PdfOptions optionsController; public HtmlToPdfController() { baseTitle = message("HtmlToPdf"); targetFileSuffix = "pdf"; } @Override public void setFileType() { setFileType(VisitHistory.FileType.Html, VisitHistory.FileType.PDF); } @Override public void initControls() { try { super.initControls(); optionsController.setControls(baseName, true); } catch (Exception e) { MyBoxLog.error(e); } } @Override public String handleFile(FxTask currentTask, File srcFile, File targetPath) { try { File target = makeTargetFile(srcFile, targetPath); if (target == null) { return message("Skip"); } String html = TextFileTools.readTexts(currentTask, srcFile); if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } if (html == null) { return message("Failed"); } String result = optionsController.html2pdf(currentTask, html, target); if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } if (message("Successful").equals(result)) { targetFileGenerated(target); } return result; } catch (Exception e) { updateLogs(e.toString()); return e.toString(); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlDataTreeSource.java
released/MyBox/src/main/java/mara/mybox/controller/ControlDataTreeSource.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.Label; import mara.mybox.db.data.DataNode; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2024-12-2 * @License Apache License Version 2.0 */ public class ControlDataTreeSource extends BaseDataTreeController { @FXML protected Label topLabel; public void setParameters(BaseDataTreeController parent, DataNode node) { try { selectionType = DataNode.SelectionType.Multiple; initDataTree(parent.nodeTable, node); } catch (Exception e) { MyBoxLog.error(e); } } public void setLabel(String label) { topLabel.setText(label); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlFFmpegOptions.java
released/MyBox/src/main/java/mara/mybox/controller/ControlFFmpegOptions.java
package mara.mybox.controller; //import com.github.kokorin.jaffree.ffprobe.FFprobeResult; //import com.github.kokorin.jaffree.ffprobe.Stream; import java.io.BufferedReader; import java.io.File; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TitledPane; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.StringTools; import mara.mybox.tools.SystemTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2020-06-02 * @License Apache License Version 2.0 */ // http://trac.ffmpeg.org/wiki/Encode/H.264 // http://trac.ffmpeg.org/wiki/Capture/Desktop // https://slhck.info/video/2017/02/24/crf-guide.html // https://slhck.info/video/2017/03/01/rate-control.html // https://www.cnblogs.com/sunny-li/p/9979796.html // http://www.luyixian.cn/news_show_306225.aspx public class ControlFFmpegOptions extends BaseTaskController { protected BaseTaskController ffmpegController; protected String executableName, executableDefault; protected File executable; protected List<String> dataTypes; protected FxTask encoderTask, muxerTask, queryTask; protected String muxer, videoCodec, audioCodec, subtitleCodec, aspect, x264preset, volumn, rtbufsize; protected boolean disableVideo, disableAudio, disableSubtitle; protected long mediaStart; protected int width, height, crf; protected float videoFrameRate, videoBitrate, audioBitrate, audioSampleRate; @FXML protected Label executableLabel; @FXML protected TextField executableInput, extensionInput, rtbufsizeInput, moreInput; @FXML protected VBox functionBox; @FXML protected ToggleGroup rotateGroup; @FXML protected RadioButton noRotateRadio, rightRotateRadio, leftRotateRadio; @FXML protected TextArea tipsArea; @FXML protected TitledPane ffmpegPane, optionsPane; @FXML protected ComboBox<String> muxerSelector, audioEncoderSelector, videoEncoderSelector, crfSelector, x264presetSelector, subtitleEncoderSelector, aspectSelector, resolutionSelector, videoFrameRateSelector, videoBitrateSelector, audioBitrateSelector, audioSampleRateSelector, volumnSelector; @FXML protected CheckBox stereoCheck; @FXML protected Button helpMeButton; @FXML protected HBox durationBox; @FXML protected CheckBox shortestCheck; public ControlFFmpegOptions() { baseTitle = message("FFmpegOptions"); TipsLabelKey = "FFmpegOptionsTips"; } @Override public void initValues() { try { super.initValues(); executableName = "FFmpegExecutable"; executableDefault = "win".equals(SystemTools.os()) ? "D:\\Programs\\ffmpeg\\bin\\ffmpeg.exe" : "/home/ffmpeg"; disableVideo = disableAudio = disableSubtitle = false; width = height = -1; videoFrameRate = 24f; videoBitrate = 5000 * 1000; audioBitrate = 192; audioSampleRate = 44100; crf = -1; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void initControls() { try { super.initControls(); if (executableInput == null) { return; } executableInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue observable, String oldValue, String newValue) { checkExecutableInput(); } }); if (functionBox != null) { functionBox.disableProperty().bind(executableInput.styleProperty().isEqualTo(UserConfig.badStyle())); } if (durationBox != null) { durationBox.setVisible(false); } rtbufsize = UserConfig.getString("FFmpegRtbufsize", ""); if (rtbufsizeInput != null) { rtbufsizeInput.setText(rtbufsize); rtbufsizeInput.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (!nv) { rtbufsize = rtbufsizeInput.getText(); UserConfig.setString("FFmpegRtbufsize", rtbufsize); } } }); } } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(executableInput, message("FFmpegExeComments")); if (moreInput != null) { NodeStyleTools.setTooltip(moreInput, message("SeparateBySpace")); } if (tipsArea != null) { tipsArea.setText(message("FFmpegArgumentsTips")); } if (crfSelector != null) { NodeStyleTools.setTooltip(crfSelector, message("CRFComments")); } if (x264presetSelector != null) { NodeStyleTools.setTooltip(x264presetSelector, message("X264PresetComments")); } } catch (Exception e) { MyBoxLog.debug(e); } } public void setParameters(BaseTaskController ffmpegController) { try { this.ffmpegController = ffmpegController; executableInput.setText(UserConfig.getString(executableName, executableDefault)); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void selectExecutable() { try { File file = FxFileTools.selectFile(this); if (file == null) { return; } executableInput.setText(file.getAbsolutePath()); } catch (Exception e) { // MyBoxLog.error(e); } } public void checkExecutableInput() { executable = null; if (helpMeButton != null) { helpMeButton.setDisable(true); } String v = executableInput.getText(); if (v == null || v.isEmpty()) { executableInput.setStyle(UserConfig.badStyle()); return; } final File file = new File(v); if (!file.exists()) { executableInput.setStyle(UserConfig.badStyle()); return; } executable = file; executableInput.setStyle(null); UserConfig.setString(executableName, file.getAbsolutePath()); readMuxers(); readEncoders(); if (helpMeButton != null) { helpMeButton.setDisable(false); } } public void readMuxers() { if (muxerSelector == null) { return; } muxerSelector.getItems().clear(); if (executable == null) { return; } // ffmpegController.tabPane.getSelectionModel().select(ffmpegController.logsTab); if (muxerTask != null) { muxerTask.cancel(); } try { List<String> command = new ArrayList<>(); command.add(executable.getAbsolutePath()); command.add("-muxers"); showCmd(command); ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true); final Process process = pb.start(); muxerTask = new FxTask<Void>(this) { private List<String> muxers, commons; @Override protected boolean handle() { error = null; muxers = new ArrayList(); commons = new ArrayList(); List<String> commonNames = new ArrayList(); commonNames.addAll(Arrays.asList("mp4", "mp3", "aiff", "au", "avi", "flv", "mov", "wav", "m4v", "hls", "rtsp")); try (BufferedReader inReader = process.inputReader(Charset.defaultCharset())) { String line; int count = 0; while ((line = inReader.readLine()) != null) { ffmpegController.showLogs(line); count++; if (count < 4 || line.length() < 5) { continue; } String muxer = line.substring(4); for (String common : commonNames) { if (muxer.startsWith(common + " ")) { commons.add(muxer); break; } } muxers.add(muxer); } } catch (Exception e) { error = e.toString(); } return true; } @Override protected void whenSucceeded() { if (error != null) { popError(error); } muxerSelector.getItems().addAll(commons); muxerSelector.getItems().addAll(muxers); muxerSelector.getItems().add(0, message("OriginalFormat")); muxerSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultMuter", newValue); } if (newValue == null || newValue.isEmpty() || message("OriginalFormat").equals(newValue) || message("NotSet").equals(newValue)) { extensionInput.setText(message("OriginalFormat")); muxer = null; return; } int pos = newValue.indexOf(' '); if (pos < 0) { muxer = newValue; } else { muxer = newValue.substring(0, pos); } if (muxer.equals("hls")) { extensionInput.setText("m3u8"); } else { extensionInput.setText(muxer); } }); muxerSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultMuter", "mp4")); } @Override protected void finalAction() { super.finalAction(); muxerTask = null; } }; start(muxerTask); process.waitFor(); } catch (Exception e) { MyBoxLog.debug(e); popError(e.toString()); } finally { muxerTask = null; } } public void readEncoders() { if (executable == null) { return; } if (audioEncoderSelector != null) { audioEncoderSelector.getItems().clear(); } if (videoEncoderSelector != null) { videoEncoderSelector.getItems().clear(); } if (subtitleEncoderSelector != null) { subtitleEncoderSelector.getItems().clear(); } if (encoderTask != null) { encoderTask.cancel(); } // ffmpegController.tabPane.getSelectionModel().select(ffmpegController.logsTab); try { List<String> command = new ArrayList<>(); command.add(executable.getAbsolutePath()); command.add("-hide_banner"); command.add("-encoders"); showCmd(command); ProcessBuilder pb = new ProcessBuilder(command).redirectErrorStream(true); final Process process = pb.start(); encoderTask = new FxTask<Void>(this) { private List<String> aEncoders, vEncoders, sEncoders, videoCommons; @Override protected boolean handle() { error = null; aEncoders = new ArrayList(); vEncoders = new ArrayList(); sEncoders = new ArrayList(); videoCommons = new ArrayList(); List<String> commonVideoNames = new ArrayList(); commonVideoNames.addAll(Arrays.asList("flv", "x264", "x265", "libvpx", "h264")); try (BufferedReader inReader = process.inputReader(Charset.defaultCharset())) { String line; int count = 0; while ((line = inReader.readLine()) != null) { ffmpegController.showLogs(line); count++; if (count < 10 || line.length() < 9) { continue; } String type = line.substring(0, 8); String encoder = line.substring(8); if (type.contains("V")) { for (String common : commonVideoNames) { if (encoder.contains(common)) { videoCommons.add(encoder); break; } } vEncoders.add(encoder); } else if (type.contains("A")) { aEncoders.add(encoder); } else if (type.contains("S")) { sEncoders.add(encoder); } } return true; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { if (audioEncoderSelector != null) { audioEncoderSelector.getItems().addAll(aEncoders); audioEncoderSelector.getItems().add(0, message("DisableAudio")); audioEncoderSelector.getItems().add(0, message("CopyAudio")); audioEncoderSelector.getItems().add(0, message("NotSet")); initAudioControls(); } if (videoEncoderSelector != null) { videoEncoderSelector.getItems().addAll(videoCommons); videoEncoderSelector.getItems().addAll(vEncoders); videoEncoderSelector.getItems().add(0, message("DisableVideo")); videoEncoderSelector.getItems().add(0, message("CopyVideo")); videoEncoderSelector.getItems().add(0, message("NotSet")); initVideoControls(); } if (subtitleEncoderSelector != null) { subtitleEncoderSelector.getItems().addAll(sEncoders); subtitleEncoderSelector.getItems().add(0, message("DisableSubtitle")); subtitleEncoderSelector.getItems().add(0, message("CopySubtitle")); subtitleEncoderSelector.getItems().add(0, message("NotSet")); initSubtitleControls(); } } @Override protected void finalAction() { super.finalAction(); encoderTask = null; } }; start(encoderTask); process.waitFor(); } catch (Exception e) { MyBoxLog.debug(e); popError(e.toString()); } finally { encoderTask = null; } } public void initAudioControls() { try { if (audioEncoderSelector != null) { audioEncoderSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAudioEncoder", newValue); } disableAudio = false; if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { audioCodec = null; return; } if (message("DisableAudio").equals(newValue)) { disableAudio = true; audioCodec = null; return; } if (message("CopyAudio").equals(newValue)) { audioCodec = "copy"; return; } int pos = newValue.indexOf(' '); if (pos < 0) { audioCodec = newValue; } else { audioCodec = newValue.substring(0, pos); } }); audioEncoderSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAudioEncoder", "aac")); } if (audioBitrateSelector != null) { audioBitrateSelector.getItems().add(message("NotSet")); audioBitrateSelector.getItems().addAll(Arrays.asList( "192kbps", "128kbps", "96kbps", "64kbps", "256kbps", "320kbps", "32kbps", "1411.2kbps", "328kbps" )); audioBitrateSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAudioBitrate", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { audioBitrate = 192; return; } try { int pos = newValue.indexOf("kbps"); String value; if (pos < 0) { value = newValue; } else { value = newValue.substring(0, pos); } float v = Float.parseFloat(value.trim()); if (v > 0) { audioBitrate = v; audioBitrateSelector.getEditor().setStyle(null); } else { audioBitrateSelector.getEditor().setStyle(UserConfig.badStyle()); } } catch (Exception e) { audioBitrateSelector.getEditor().setStyle(UserConfig.badStyle()); } }); audioBitrateSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAudioBitrate", "192kbps")); } if (audioSampleRateSelector != null) { audioSampleRateSelector.getItems().add(message("NotSet")); audioSampleRateSelector.getItems().addAll(Arrays.asList(message("48000Hz"), message("44100Hz"), message("96000Hz"), message("8000Hz"), message("11025Hz"), message("22050Hz"), message("24000Hz"), message("32000Hz"), message("50000Hz"), message("47250Hz"), message("192000Hz") )); audioSampleRateSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAudioSampleRate", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { audioSampleRate = 44100; return; } try { int pos = newValue.indexOf("Hz"); String value; if (pos < 0) { value = newValue; } else { value = newValue.substring(0, pos); } int v = Integer.parseInt(value.trim()); if (v > 0) { audioSampleRate = v; audioSampleRateSelector.getEditor().setStyle(null); } else { audioSampleRateSelector.getEditor().setStyle(UserConfig.badStyle()); } } catch (Exception e) { audioSampleRateSelector.getEditor().setStyle(UserConfig.badStyle()); } }); audioSampleRateSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAudioSampleRate", message("44100Hz"))); } if (volumnSelector != null) { volumnSelector.getItems().addAll(Arrays.asList(message("NotSet"), message("10dB"), message("20dB"), message("5dB"), message("30dB"), message("-10dB"), message("-20dB"), message("-5dB"), message("-30dB"), message("1.5"), message("1.25"), message("2"), message("3"), message("0.5"), message("0.8"), message("0.6") )); volumnSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAudioVolumn", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { volumn = null; return; } volumn = newValue; }); volumnSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAudioVolumn", message("NotSet"))); } } catch (Exception e) { MyBoxLog.error(e); } } public void initVideoControls() { try { setH264(); setCRF(); if (videoEncoderSelector != null) { videoEncoderSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { setVcodec(newValue); setH264(); setCRF(); }); videoEncoderSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultVideoEncoder", defaultVideoEcodec())); } if (aspectSelector != null) { aspectSelector.getItems().addAll(Arrays.asList(message("NotSet"), "4:3", "16:9" )); aspectSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultAspect", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { aspect = null; return; } aspect = newValue; }); aspectSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultAspect", message("NotSet"))); } // http://ffmpeg.org/ffmpeg-utils.html if (resolutionSelector != null) { resolutionSelector.getItems().add(message("NotSet")); resolutionSelector.getItems().addAll(Arrays.asList( "ntsc 720x480", "pal 720x576", "qntsc 352x240", "qpal 352x288", "sntsc 640x480", "spal 768x576", "film 352x240", "ntsc-film 352x240", "sqcif 128x96", "qcif 176x144", "cif 352x288", "4cif 704x576", "16cif 1408x1152", "qqvga 160x120", "qvga 320x240", "vga 640x480", "svga 800x600", "xga 1024x768", "uxga 1600x1200", "qxga 2048x1536", "sxga 1280x1024", "qsxga 2560x2048", "hsxga 5120x4096", "wvga 852x480", "wxga 1366x768", "wsxga 1600x1024", "wuxga 1920x1200", "woxga 2560x1600", "wqsxga 3200x2048", "wquxga 3840x2400", "whsxga 6400x4096", "whuxga 7680x4800", "cga 320x200", "ega 640x350", "hd480 852x480", "hd720 1280x720", "hd1080 1920x1080", "2k 2048x1080", "2kflat 1998x1080", "2kscope 2048x858", "4k 4096x2160", "4kflat 3996x2160", "4kscope 4096x1716", "nhd 640x360", "hqvga 240x160", "wqvga 400x240", "fwqvga 432x240", "hvga 480x320", "qhd 960x540", "2kdci 2048x1080", "4kdci 4096x2160", "uhd2160 3840x2160", "uhd4320 7680x4320" )); resolutionSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultResolution", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { width = height = -1; return; } try { String value = newValue.substring(newValue.lastIndexOf(' ') + 1); int pos = value.indexOf('x'); width = Integer.parseInt(value.substring(0, pos)); height = Integer.parseInt(value.substring(pos + 1)); } catch (Exception e) { } }); String dres = UserConfig.getString("ffmpegDefaultResolution", "ntsc 720x480"); resolutionSelector.getSelectionModel().select(dres); } if (videoFrameRateSelector != null) { videoFrameRateSelector.getItems().add(message("NotSet")); videoFrameRateSelector.getItems().addAll(Arrays.asList( "ntsc 30000/1001", "pal 25/1", "qntsc 30000/1001", "qpal 25/1", "sntsc 30000/1001", "spal 25/1", "film 24/1", "ntsc-film 24000/1001" )); videoFrameRateSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultFrameRate", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { videoFrameRate = 24f; return; } try { String value = newValue.substring(newValue.lastIndexOf(' ') + 1); int pos = value.indexOf('/'); videoFrameRate = Integer.parseInt(value.substring(0, pos)) * 1f / Integer.parseInt(value.substring(pos + 1)); } catch (Exception e) { } }); videoFrameRateSelector.getSelectionModel().select(UserConfig.getString("ffmpegDefaultFrameRate", "ntsc 30000/1001")); } if (videoBitrateSelector != null) { videoBitrateSelector.getItems().add(message("NotSet")); videoBitrateSelector.getItems().addAll(Arrays.asList( "1800kbps", "1600kbps", "1300kbps", "2400kbps", "1150kbps", "5mbps", "6mbps", "8mbps", "16mbps", "4mbps", "40mbps", "65mbps", "10mbps", "20mbps", "15mbps", "3500kbps", "3000kbps", "2000kbps", "1000kbps", "800kbps", "500kbps", "250kbps", "120kbps", "60kbps", "30kbps" )); videoBitrateSelector.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String oldValue, String newValue) -> { if (newValue != null && !newValue.isEmpty()) { UserConfig.setString("ffmpegDefaultVideoBitrate", newValue); } if (newValue == null || newValue.isEmpty() || message("NotSet").equals(newValue)) { videoBitrate = 1800; return; } try { int pos = newValue.indexOf("kbps"); if (pos < 0) { pos = newValue.indexOf("mbps"); if (pos < 0) {
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/Data2DPasteContentInSystemClipboardController.java
released/MyBox/src/main/java/mara/mybox/controller/Data2DPasteContentInSystemClipboardController.java
package mara.mybox.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.input.KeyEvent; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2021-11-27 * @License Apache License Version 2.0 */ public class Data2DPasteContentInSystemClipboardController extends BaseData2DPasteController { @FXML protected ControlData2DSystemClipboard boardController; public Data2DPasteContentInSystemClipboardController() { baseTitle = message("PasteContentInSystemClipboard"); } public void setParameters(Data2DManufactureController target, String text) { try { this.parentController = target; setParameters(target); boardController.loadNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { loadDef(boardController.textData); } }); boardController.load(text); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean handleKeyEvent(KeyEvent event) { if (boardController.handleKeyEvent(event)) { return true; } return super.handleKeyEvent(event); } /* static */ public static Data2DPasteContentInSystemClipboardController open(Data2DManufactureController parent, String text) { try { Data2DPasteContentInSystemClipboardController controller = (Data2DPasteContentInSystemClipboardController) WindowTools.referredTopStage( parent, Fxmls.Data2DPasteContentInSystemClipboardFxml); controller.setParameters(parent, text); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BaseController_MouseEvents.java
released/MyBox/src/main/java/mara/mybox/controller/BaseController_MouseEvents.java
package mara.mybox.controller; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-7-27 * @License Apache License Version 2.0 */ public abstract class BaseController_MouseEvents extends BaseController_KeyEvents { private MouseEvent mouseEvent; public void monitorMouseEvents() { try { if (thisPane != null) { thisPane.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> { mouseEvent = event; if (mouseEventsFilter(event)) { MyBoxLog.debug("consume:" + this.getClass() + " source:" + event.getSource().getClass() + " target:" + event.getTarget().getClass() + " count:" + event.getClickCount() + " rightClick:" + (event.getButton() == MouseButton.SECONDARY)); event.consume(); } mouseEvent = null; }); } } catch (Exception e) { MyBoxLog.error(e); } } // return whether handled public boolean mouseEventsFilter(MouseEvent event) { MyBoxLog.debug("consume:" + this.getClass() + " source:" + event.getSource().getClass() + " target:" + event.getTarget().getClass() + " count:" + event.getClickCount() + " rightClick:" + (event.getButton() == MouseButton.SECONDARY)); if (event.isSecondaryButtonDown()) { return rightClickFilter(event); } return false; } public boolean rightClickFilter(MouseEvent event) { return false; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/RemotePathSynchronizeFromLocalController.java
released/MyBox/src/main/java/mara/mybox/controller/RemotePathSynchronizeFromLocalController.java
package mara.mybox.controller; import java.io.File; import java.util.List; import javafx.fxml.FXML; import javafx.scene.layout.VBox; import mara.mybox.data.FileNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-3-15 * @License Apache License Version 2.0 */ public class RemotePathSynchronizeFromLocalController extends DirectorySynchronizeController { @FXML protected ControlRemoteConnection remoteController; @FXML protected VBox sourceBox, remoteBox; public RemotePathSynchronizeFromLocalController() { baseTitle = message("RemotePathSynchronizeFromLocal"); } @Override public void initTarget() { try { remoteController.setParameters(this); } catch (Exception e) { MyBoxLog.debug(e); } } @Override protected boolean checkTarget() { return remoteController.pickProfile(); } @Override public void beforeTask() { super.beforeTask(); sourceBox.setDisable(true); remoteBox.setDisable(true); } @Override public boolean doTask(FxTask currentTask) { try { return remoteController.connect(currentTask) && synchronize(currentTask, remoteController.currentConnection.getPath()); } catch (Exception e) { showLogs(e.toString()); return false; } } @Override public void afterTask(boolean ok) { remoteController.disconnect(); sourceBox.setDisable(false); remoteBox.setDisable(false); } @Override public FileNode targetNode(String targetName) { return remoteController.FileNode(targetName); } @Override public List<FileNode> targetChildren(FxTask currentTask, FileNode targetNode) { return remoteController.children(currentTask, targetNode); } @Override public void deleteTargetFile(FxTask currentTask, FileNode targetNode) { if (targetNode != null) { remoteController.delete(currentTask, targetNode.nodeFullName()); } } @Override public void targetMkdirs(File srcFile, FileNode targetNode) { if (targetNode != null) { remoteController.mkdirs(targetNode.nodeFullName(), copyAttr.isCopyMTime() && srcFile != null ? (int) (srcFile.lastModified() / 1000) : -1, copyAttr.getPermissions()); } } @Override public boolean copyFile(FxTask currentTask, File sourceFile, FileNode targetNode) { try { if (targetNode == null) { return false; } return remoteController.put(currentTask, sourceFile, targetNode.nodeFullName(), copyAttr.isCopyMTime(), copyAttr.getPermissions()); } catch (Exception e) { showLogs(e.toString()); return false; } } @Override public boolean isModified(File srcFile, FileNode targetNode) { int stime = (int) (srcFile.lastModified() / 1000); int ttime = (int) (targetNode.getModifyTime() / 1000); return stime > ttime; } @FXML @Override public void openTarget() { RemotePathManageController.open(remoteController.currentConnection); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/IccProfileEditorController.java
released/MyBox/src/main/java/mara/mybox/controller/IccProfileEditorController.java
package mara.mybox.controller; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.Event; import javafx.fxml.FXML; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import mara.mybox.color.IccHeader; import mara.mybox.color.IccProfile; import mara.mybox.color.IccTag; import mara.mybox.color.IccTagType; import mara.mybox.color.IccTags; import mara.mybox.color.IccXML; import mara.mybox.db.data.FileBackup; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.data.VisitHistoryTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.NodeTools; import mara.mybox.fxml.RecentVisitMenu; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.ByteTools; import static mara.mybox.tools.ByteTools.bytesToHexFormat; import mara.mybox.tools.DateTools; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.TextFileTools; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; import mara.mybox.value.FileFilters; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-5-13 * @Description * @License Apache License Version 2.0 */ public class IccProfileEditorController extends ChromaticityBaseController { protected SourceType sourceType; protected String embedICCName, externalDataName; protected boolean isIccFile, inputsValid; protected IccProfile profile; private IccHeader header; private IccTags tags; protected ObservableList<IccTag> tagsTable = FXCollections.observableArrayList(); @FXML protected ComboBox<String> embedBox, cmmTypeBox, deviceClassBox, colorSpaceBox, PCSTypeBox, platformBox, manufacturerBox, intentBox, creatorBox; @FXML protected TextField profileVersionInput, createTimeInput, profileFileInput, deviceModelInput, xInput, yInput, zInput, profileIdInput, spectralPCSInput, spectralPCSRangeInput, bispectralPCSRangeInput, mcsInput, subClassInput, subclassVersionInput, xOutput, yOutput, zOutput, tagDisplay, tagNameDisplay, tagTypeDisplay, tagOffsetDisplay, tagSizeDisplay, maxDecodeInput; @FXML protected CheckBox embedCheck, independentCheck, subsetCheck, transparentcyCheck, matteCheck, negativeCheck, bwCheck, paperCheck, texturedCheck, isotropicCheck, selfLuminousCheck, idAutoCheck, lutNormalizeCheck, openExportCheck; @FXML protected Label infoLabel, cmmTypeMarkLabel, deviceClassMarkLabel, colorSpaceMarkLabel, PCSTypeMarkLabel, platformMarkLabel, manufacturerMarkLabel, intentMarkLabel, creatorMarkLabel, profileVersionMarkLabel, createTimeMarkLabel, profileFileMarkLabel, deviceModelMarkLabel, xMarkLabel, yMarkLabel, zMarkLabel, embedMarkLabel, independentMarkLabel, subsetMarkLabel, transparentcyMarkLabel, matteMarkLabel, negativeMarkLabel, bwMarkLabel, paperMarkLabel, texturedMarkLabel, isotropicMarkLabel, selfLuminousMarkLabel, cieDataLabel; @FXML protected TextArea summaryArea, xmlArea, tagDescDisplay, tagDataDisplay, tagBytesDisplay; @FXML protected TableView<IccTag> tagsTableView; @FXML protected TableColumn<IccTag, String> tagColumn, nameColumn, typeColumn; @FXML protected TableColumn<IccTag, Integer> offsetColumn, sizeColumn; @FXML protected VBox headerBox, tagDataBox, csInputBox, chromaticDiagramBox; @FXML protected TabPane displayPane; @FXML protected Tab tagDataTab; @FXML protected Button refreshHeaderButton, refreshXmlButton, exportXmlButton, backupButton; @FXML protected FlowPane opsPane; protected enum SourceType { Embed, Internal_File, External_File, External_Data }; public IccProfileEditorController() { baseTitle = message("IccProfileEditor"); TipsLabelKey = "IccProfileTips"; } @Override public void setFileType() { setFileType(VisitHistory.FileType.Icc); } @Override public void initControls() { try { super.initControls(); sourceFile = null; embedICCName = null; initToolbar(); initHeaderControls(); initTagsTable(); initOptions(); opsPane.setDisable(true); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(maxDecodeInput, new Tooltip(message("MaxDecodeComments"))); } catch (Exception e) { MyBoxLog.debug(e); } } protected void initToolbar() { try { embedBox.getItems().addAll(Arrays.asList( "sRGB", "XYZ", "PYCC", "GRAY", "LINEAR_RGB", "ECI_RGB_v2_ICCv4.icc", "ECI_CMYK.icc", "AdobeRGB_1998.icc", "Adobe_AppleRGB.icc", "Adobe_ColorMatchRGB.icc", "AdobeCMYK_CoatedFOGRA27.icc", "AdobeCMYK_CoatedFOGRA39.icc", "AdobeCMYK_UncoatedFOGRA29.icc", "AdobeCMYK_WebCoatedFOGRA28.icc", "AdobeCMYK_JapanColor2001Coated.icc", "AdobeCMYK_JapanColor2001Uncoated.icc", "AdobeCMYK_JapanColor2002Newspaper.icc", "AdobeCMYK_JapanWebCoated.icc", "AdobeCMYK_USSheetfedCoated.icc", "AdobeCMYK_USSheetfedUncoated.icc", "AdobeCMYK_USWebCoatedSWOP.icc", "AdobeCMYK_USWebUncoated.icc" )); embedBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { iccChanged(); } }); // embedBox.getSelectionModel().select(0); // saveButton.disableProperty().bind(profileVersionInput.styleProperty().isEqualTo(badStyle) // .or(createTimeInput.styleProperty().isEqualTo(badStyle)) // .or(xInput.styleProperty().isEqualTo(badStyle)) // .or(yInput.styleProperty().isEqualTo(badStyle)) // .or(zInput.styleProperty().isEqualTo(badStyle)) // ); // saveAsButton.disableProperty().bind(saveButton.disableProperty() // ); } catch (Exception e) { MyBoxLog.error(e); } } protected void initHeaderControls() { try { List<String> manuList = new ArrayList<>(); for (String[] item : IccHeader.DeviceManufacturers) { manuList.add(item[0] + AppValues.Indent + item[1]); } cmmTypeBox.getItems().addAll(manuList); cmmTypeBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (!cmmTypeBox.getItems().contains(newValue)) { ValidationTools.setEditorWarnStyle(cmmTypeBox); } else { ValidationTools.setEditorNormal(cmmTypeBox); } if (isSettingValues) { return; } cmmTypeMarkLabel.setText("*"); profileChanged(); } }); profileVersionInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (isSettingValues) { return; } profileVersionMarkLabel.setText("*"); profileChanged(); } }); List<String> classList = new ArrayList<>(); for (String[] item : IccHeader.ProfileDeviceClasses) { classList.add(item[0] + AppValues.Indent + message(item[1])); } deviceClassBox.getItems().addAll(classList); deviceClassBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (isSettingValues) { return; } deviceClassMarkLabel.setText("*"); profileChanged(); } }); List<String> csList = Arrays.asList(IccHeader.ColorSpaceTypes); colorSpaceBox.getItems().addAll(csList); colorSpaceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (!colorSpaceBox.getItems().contains(newValue)) { ValidationTools.setEditorWarnStyle(colorSpaceBox); } else { ValidationTools.setEditorNormal(colorSpaceBox); } if (isSettingValues) { return; } colorSpaceMarkLabel.setText("*"); profileChanged(); } }); PCSTypeBox.getItems().addAll(Arrays.asList(IccHeader.PCSTypes)); PCSTypeBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (isSettingValues) { return; } PCSTypeMarkLabel.setText("*"); profileChanged(); } }); createTimeInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (IccTagType.dateTimeBytes(newValue) != null) { createTimeInput.setStyle(null); } else { createTimeInput.setStyle(UserConfig.badStyle()); } if (isSettingValues) { return; } createTimeMarkLabel.setText("*"); profileChanged(); } }); profileFileInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (isSettingValues) { return; } profileFileMarkLabel.setText("*"); profileChanged(); } }); List<String> platformsList = new ArrayList<>(); for (String[] item : IccHeader.PrimaryPlatforms) { platformsList.add(item[0] + AppValues.Indent + item[1]); } platformBox.getItems().addAll(platformsList); platformBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (isSettingValues) { return; } platformMarkLabel.setText("*"); profileChanged(); } }); embedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } embedMarkLabel.setText("*"); profileChanged(); } }); independentCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } independentMarkLabel.setText("*"); profileChanged(); } }); subsetCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } subsetMarkLabel.setText("*"); profileChanged(); } }); manufacturerBox.getItems().addAll(manuList); manufacturerBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (isSettingValues) { return; } if (!manufacturerBox.getItems().contains(newValue)) { ValidationTools.setEditorWarnStyle(manufacturerBox); } else { ValidationTools.setEditorNormal(manufacturerBox); } manufacturerMarkLabel.setText("*"); profileChanged(); } }); deviceModelInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (isSettingValues) { return; } deviceModelMarkLabel.setText("*"); profileChanged(); } }); transparentcyCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } transparentcyMarkLabel.setText("*"); profileChanged(); } }); matteCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } matteMarkLabel.setText("*"); profileChanged(); } }); negativeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } negativeMarkLabel.setText("*"); profileChanged(); } }); bwCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } bwMarkLabel.setText("*"); profileChanged(); } }); paperCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } paperMarkLabel.setText("*"); profileChanged(); } }); texturedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } texturedMarkLabel.setText("*"); profileChanged(); } }); isotropicCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } isotropicMarkLabel.setText("*"); profileChanged(); } }); selfLuminousCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } selfLuminousMarkLabel.setText("*"); profileChanged(); } }); List<String> intents = new ArrayList<>(); for (String item : IccHeader.RenderingIntents) { intents.add(message(item)); } intentBox.getItems().addAll(intents); intentBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (isSettingValues) { return; } intentMarkLabel.setText("*"); profileChanged(); } }); xInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { try { double v = Double.parseDouble(newValue); xInput.setStyle(null); } catch (Exception e) { xInput.setStyle(UserConfig.badStyle()); } if (isSettingValues) { return; } xMarkLabel.setText("*"); profileChanged(); } }); yInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { try { double v = Double.parseDouble(newValue); yInput.setStyle(null); } catch (Exception e) { yInput.setStyle(UserConfig.badStyle()); } if (isSettingValues) { return; } yMarkLabel.setText("*"); profileChanged(); } }); zInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { try { double v = Double.parseDouble(newValue); zInput.setStyle(null); } catch (Exception e) { zInput.setStyle(UserConfig.badStyle()); } if (isSettingValues) { return; } zMarkLabel.setText("*"); profileChanged(); } }); creatorBox.getItems().addAll(manuList); creatorBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (!creatorBox.getItems().contains(newValue)) { ValidationTools.setEditorWarnStyle(creatorBox); } else { ValidationTools.setEditorNormal(creatorBox); } if (isSettingValues) { return; } creatorMarkLabel.setText("*"); profileChanged(); } }); } catch (Exception e) { MyBoxLog.error(e); } } protected void initTagsTable() { tagColumn.setCellValueFactory(new PropertyValueFactory<>("tag")); nameColumn.setCellValueFactory(new PropertyValueFactory<>("name")); typeColumn.setCellValueFactory(new PropertyValueFactory<>("type")); offsetColumn.setCellValueFactory(new PropertyValueFactory<>("offset")); sizeColumn.setCellValueFactory(new PropertyValueFactory<>("size")); tagsTableView.setItems(tagsTable); tagsTableView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue ov, Object t, Object t1) { IccTag selected = tagsTableView.getSelectionModel().getSelectedItem(); displayTagData(selected); } }); } @Override public void initOptions() { maxDecodeInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkMaxDecode(); } }); maxDecodeInput.setText(UserConfig.getInt("ICCMaxDecodeNumber", 500) + ""); lutNormalizeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean("LutNormalize", newValue); } }); lutNormalizeCheck.setSelected(UserConfig.getBoolean("LutNormalize", true)); } private void checkMaxDecode() { try { String s = maxDecodeInput.getText().trim(); if (s.isEmpty()) { xInput.setStyle(null); UserConfig.setInt("ICCMaxDecodeNumber", Integer.MAX_VALUE); return; } int v = Integer.parseInt(s); if (v > 0) { UserConfig.setInt("ICCMaxDecodeNumber", v); xInput.setStyle(null); } else { xInput.setStyle(UserConfig.badStyle()); } } catch (Exception e) { xInput.setStyle(UserConfig.badStyle()); } } @Override public boolean afterSceneLoaded() { if (!super.afterSceneLoaded()) { return false; } String name = getCurrentName(); if (name != null) { myStage.setTitle(getBaseTitle() + " " + name); } return true; } private String getCurrentName() { if (null != sourceType) { switch (sourceType) { case Internal_File: case External_File: if (sourceFile != null) { return sourceFile.getAbsolutePath(); } break; case Embed: if (embedICCName != null) { return message("JavaEmbeddedColorModel") + ": " + embedICCName; } break; case External_Data: if (externalDataName != null) { return externalDataName; } break; default: break; } } return ""; } @Override public void selectSourceFileDo(File file) { if (file == null) { return; } recordFileOpened(file); sourceType = SourceType.External_File; openProfile(file.getAbsolutePath()); } private void iccChanged() { if (isSettingValues) { return; } String name = embedBox.getSelectionModel().getSelectedItem(); if (name == null || name.trim().isEmpty()) { return; } switch (name) { case "sRGB": case "XYZ": case "PYCC": case "GRAY": case "LINEAR_RGB": sourceType = SourceType.Embed; openProfile(name); break; default: sourceType = SourceType.Internal_File; openProfile(name); } } public void externalData(String name, byte[] data) { try { if (data == null) { return; } sourceType = SourceType.External_Data; sourceFile = null; externalDataName = name; embedBox.getSelectionModel().clearSelection(); profile = new IccProfile(data); displayProfileData(); } catch (Exception e) { MyBoxLog.error(e); } } private void openProfile(final String name) { if (name == null || name.trim().isEmpty()) { return; } if (task != null) { task.cancel(); } final String inputName; if (sourceType == SourceType.Embed) { inputName = message("JavaEmbeddedColorModel") + ": " + name; } else { inputName = message("File") + ": " + name; } task = new FxSingletonTask<Void>(this) { private File file = null; private IccProfile p; @Override protected boolean handle() { try { switch (sourceType) { case Embed: p = new IccProfile(name); break; case Internal_File: file = mara.mybox.fxml.FxFileTools.getInternalFile("/data/ICC/" + name, "ICC", name); p = new IccProfile(file); break; case External_File: file = new File(name); p = new IccProfile(file); } } catch (Exception e) { error = e.toString(); } return p != null && p.getHeader() != null; } @Override protected void whenSucceeded() { isIccFile = sourceType != SourceType.Embed; if (isIccFile) { sourceFile = file; isSettingValues = true; embedICCName = null; isSettingValues = false; } else { embedICCName = name; sourceFile = null; } if (sourceType == SourceType.External_File) { embedBox.getSelectionModel().clearSelection(); } profile = p; displayProfileData(); } @Override protected void whenFailed() { if (error == null) { if (p != null && p.getError() != null) { error = p.getError(); } else { error = message("Invalid"); } } popError(inputName + " " + error); } }; start(task, inputName + " " + message("Loading...")); } private void displayProfileData() { if (profile == null || !profile.isIsValid()) { popError(message("IccInvalid")); return; } if (task != null) { task.cancel(); } profile.setNormalizeLut(lutNormalizeCheck.isSelected()); infoLabel.setText(getCurrentName()); if (myStage != null) { myStage.setTitle(getBaseTitle() + " " + getCurrentName()); } resetMarkLabel(headerBox); backupButton.setDisable(sourceFile == null); inputsValid = true; task = new FxSingletonTask<Void>(this) { private String xml; @Override protected boolean handle() { header = profile.getHeader(); header.readFields(); tags = profile.getTags(); tags.readTags(); xml = IccXML.iccXML(header, tags); if (xml == null) { error = message("IccInvalid"); return false; } else { return true; } } @Override protected void whenSucceeded() { displaySummary(); initHeaderInputs(); makeTagsInputs(); displayTagsTable(); displayXML(xml); opsPane.setDisable(false); } }; start(task); } private void displaySummary() { summaryArea.clear(); if (header == null) { return; } try { LinkedHashMap<String, IccTag> fields = header.getFields(); String s = message("ProfileSize") + ": " + header.value("ProfileSize"); List<IccTag> tagsList = tags.getTags(); if (tagsList != null) { s += " " + message("TagsNumber") + ": " + tagsList.size(); } String name = getCurrentName(); infoLabel.setText(name + "\n" + message("ProfileSize") + ": " + header.value("ProfileSize") + ((tagsList != null) ? "\n" + message("TagsNumber") + ": " + tagsList.size() : "")); s = name + "\n" + s + "\n\n"; for (String key : fields.keySet()) { IccTag field = fields.get(key); switch (key) { case "ProfileFlagIndependently": case "ProfileFlagMCSSubset": case "DeviceAttributeMatte": case "DeviceAttributeNegative": case "DeviceAttributeBlackOrWhite": case "DeviceAttributePaperBased": case "DeviceAttributeTextured": case "DeviceAttributeIsotropic": case "DeviceAttributeSelfLuminous": case "PCCIlluminantY": case "PCCIlluminantZ":
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BaseShapeTransformController.java
released/MyBox/src/main/java/mara/mybox/controller/BaseShapeTransformController.java
package mara.mybox.controller; import java.awt.geom.Rectangle2D; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import mara.mybox.data.DoublePoint; import mara.mybox.data.DoubleShape; import mara.mybox.dev.MyBoxLog; import static mara.mybox.tools.DoubleTools.imageScale; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-8-16 * @License Apache License Version 2.0 */ public class BaseShapeTransformController extends BaseInputController { protected BaseShapeController imageController; protected float x, y; protected DoubleShape shapeData; protected DoublePoint point; @FXML protected TextField xInput, yInput; @FXML protected Button pointButton; @FXML protected Label infoLabel; public void setParameters(BaseShapeController parent, DoubleShape shapeData, DoublePoint point) { try { super.setParameters(parent, null); imageController = parent; this.shapeData = shapeData; this.point = point; String info = DoubleShape.values(shapeData); if (point != null) { info += "\n" + message("Point") + ": " + imageScale(point.getX()) + ", " + imageScale(point.getY()); } infoLabel.setText(info); if (pointButton != null) { pointButton.setVisible(point != null); } } catch (Exception e) { MyBoxLog.debug(e); } } @FXML public void shapeCenter() { if (shapeData == null) { return; } DoublePoint center = DoubleShape.getCenter(shapeData); if (center == null) { return; } xInput.setText(imageScale(center.getX()) + ""); yInput.setText(imageScale(center.getY()) + ""); } @FXML public void shapeLeftTop() { if (shapeData == null) { return; } Rectangle2D bounds = DoubleShape.getBound(shapeData); if (bounds == null) { return; } xInput.setText(imageScale(bounds.getMinX()) + ""); yInput.setText(imageScale(bounds.getMinY()) + ""); } @FXML public void shapeRightBottom() { if (shapeData == null) { return; } Rectangle2D bounds = DoubleShape.getBound(shapeData); if (bounds == null) { return; } xInput.setText(imageScale(bounds.getMaxX()) + ""); yInput.setText(imageScale(bounds.getMaxY()) + ""); } @FXML public void shapeLeftBottom() { if (shapeData == null) { return; } Rectangle2D bounds = DoubleShape.getBound(shapeData); if (bounds == null) { return; } xInput.setText(imageScale(bounds.getMinX()) + ""); yInput.setText(imageScale(bounds.getMaxY()) + ""); } @FXML public void shapeRightTop() { if (shapeData == null) { return; } Rectangle2D bounds = DoubleShape.getBound(shapeData); if (bounds == null) { return; } xInput.setText(imageScale(bounds.getMaxX()) + ""); yInput.setText(imageScale(bounds.getMinY()) + ""); } @FXML public void imageCenter() { if (imageController == null) { return; } xInput.setText(imageScale(imageController.imageWidth() / 2) + ""); yInput.setText(imageScale(imageController.imageHeight() / 2) + ""); } @FXML public void imageLeftTop() { if (shapeData == null) { return; } xInput.setText("0"); yInput.setText("0"); } @FXML public void imageRightBottom() { if (shapeData == null) { return; } xInput.setText(imageScale(imageController.imageWidth()) + ""); yInput.setText(imageScale(imageController.imageHeight()) + ""); } @FXML public void imageLeftBottom() { if (shapeData == null) { return; } xInput.setText("0"); yInput.setText(imageScale(imageController.imageHeight()) + ""); } @FXML public void imageRightTop() { if (shapeData == null) { return; } xInput.setText(imageScale(imageController.imageWidth()) + ""); yInput.setText("0"); } @FXML public void point() { if (point == null) { return; } xInput.setText(imageScale(point.getX()) + ""); yInput.setText(imageScale(point.getY()) + ""); } @FXML @Override public boolean checkInput() { if (shapeData == null) { popError(message("noData")); return false; } try { x = Float.parseFloat(xInput.getText()); } catch (Exception e) { popError(message("InvalidValue") + ": x"); return false; } try { y = Float.parseFloat(yInput.getText()); } catch (Exception e) { popError(message("InvalidValue") + ": y"); return false; } return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/RemotePathPutController.java
released/MyBox/src/main/java/mara/mybox/controller/RemotePathPutController.java
package mara.mybox.controller; import java.io.File; import java.text.MessageFormat; import java.util.LinkedHashMap; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import mara.mybox.data.FileInformation; import mara.mybox.data.FileNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2023-3-15 * @License Apache License Version 2.0 */ public class RemotePathPutController extends BaseBatchFileController { protected RemotePathManageController manageController; protected String targetPathName; protected int permissions; @FXML protected TextField targetPathInput; @FXML protected Label hostLabel; @FXML protected CheckBox copyMtimeCheck, permissionCheck; @FXML protected TextField permissionInput; public RemotePathPutController() { baseTitle = message("RemotePathPut"); } public void setParameters(RemotePathManageController manageController) { try { this.manageController = manageController; logsTextArea = manageController.logsTextArea; logsMaxChars = manageController.logsMaxChars; verboseCheck = manageController.verboseCheck; TreeItem<FileNode> item = manageController.filesTreeView.getSelectionModel().getSelectedItem(); if (item == null) { item = manageController.filesTreeView.getRoot(); } if (item != null && item.getValue() != null) { targetPathName = item.getValue().path(false); targetPathInput.setText(targetPathName); targetPathInput.selectEnd(); } hostLabel.setText(message("Host") + ": " + manageController.remoteController.host()); copyMtimeCheck.setSelected(UserConfig.getBoolean(baseName + "CopyMtime", true)); copyMtimeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopyMtime", nv); } }); permissionCheck.setSelected(UserConfig.getBoolean(baseName + "SetPermissions", false)); permissionCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "SetPermissions", nv); } }); } catch (Exception e) { MyBoxLog.error(e); popError(e.toString()); } } @Override public boolean makeMoreParameters() { targetPathName = targetPathInput.getText(); if (targetPathName == null || targetPathName.isBlank()) { popError(message("InvalidParameter") + ": " + message("TargetPath")); return false; } permissions = -1; if (permissionCheck.isSelected()) { try { permissions = Integer.parseInt(permissionInput.getText(), 8); UserConfig.setString(baseName + "Permissions", permissionInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("Permissions")); return false; } } if (manageController.task != null) { manageController.task.cancel(); } manageController.tabPane.getSelectionModel().select(manageController.logsTab); manageController.requestMouse(); return super.makeMoreParameters(); } @FXML @Override public void startAction() { targetFilesCount = 0; targetFiles = new LinkedHashMap<>(); runTask(); } @Override public void startTask() { super.startAction(); } @Override public boolean beforeHandleFiles(FxTask currentTask) { manageController.task = task; manageController.remoteController.task = task; return manageController.checkConnection() && checkDirectory(currentTask, null, targetPathName); } @Override public String handleFile(FxTask currentTask, FileInformation info) { try { if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } File file = info.getFile(); if (file == null || !file.isFile() || !match(file)) { return message("Skip" + ": " + file); } return handleFileToPath(currentTask, file, targetPathName); } catch (Exception e) { return e.toString(); } } @Override public String handleFileToPath(FxTask currentTask, File srcFile, String targetPath) { try { String targetName = makeTargetPathFilename(srcFile, targetPath); if (targetName == null) { return message("Skip"); } targetName = manageController.remoteController.fixFilename(targetName); showLogs("put " + srcFile.getAbsolutePath() + " " + targetName); if (manageController.remoteController.put(currentTask, srcFile, targetName, copyMtimeCheck.isSelected(), permissions)) { showLogs(MessageFormat.format(message("FilesGenerated"), targetName)); return message("Successful"); } else { return message("Failed"); } } catch (Exception e) { showLogs(e.toString()); return null; } } @Override public String handleDirectory(FxTask currentTask, FileInformation info) { try { File dir = info.getFile(); dirFilesNumber = dirFilesHandled = 0; String targetDir = targetPathName; if (createDirectories) { targetDir += "/" + dir.getName(); if (!checkDirectory(currentTask, dir, targetDir)) { return message("Failed"); } } handleDirectory(currentTask, dir, targetDir); return MessageFormat.format(message("DirHandledSummary"), dirFilesNumber, dirFilesHandled); } catch (Exception e) { showLogs(e.toString()); return message("Failed"); } } @Override public boolean checkDirectory(FxTask currentTask, File srcFile, String pathname) { try { if (pathname == null) { return false; } return manageController.remoteController.mkdirs(pathname, copyMtimeCheck.isSelected() && srcFile != null ? (int) (srcFile.lastModified() / 1000) : -1, permissions); } catch (Exception e) { showLogs(e.toString()); return false; } } @Override protected void taskCanceled() { super.taskCanceled(); if (manageController != null) { manageController.disconnect(); } } @Override public void afterTask(boolean ok) { super.afterTask(ok); if (manageController != null) { manageController.loadPath(); } } /* static methods */ public static RemotePathPutController open(RemotePathManageController manageController) { try { if (manageController == null) { return null; } RemotePathPutController controller = (RemotePathPutController) WindowTools.referredTopStage( manageController, Fxmls.RemotePathPutFxml); controller.setParameters(manageController); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImageShapeOptionsController.java
released/MyBox/src/main/java/mara/mybox/controller/ImageShapeOptionsController.java
package mara.mybox.controller; import java.util.Arrays; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import mara.mybox.controller.BaseShapeController_Base.AnchorShape; import mara.mybox.data.ShapeStyle; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2023-11-6 * @License Apache License Version 2.0 */ public class ImageShapeOptionsController extends ImageOptionsController { protected BaseShapeController shapeController; @FXML protected VBox shapeBox; @FXML protected FlowPane strokePane; @FXML protected ComboBox<String> strokeWidthSelector, anchorSizeSelector; @FXML protected ControlColorSet strokeColorController, anchorColorController; @FXML protected ToggleGroup anchorShapeGroup; @FXML protected RadioButton anchorRectRadio, anchorCircleRadio, anchorNameRadio; @Override public void initControls() { try { super.initControls(); strokeWidthSelector.getItems().addAll(Arrays.asList("2", "1", "3", "4", "5", "6", "7", "8", "9", "10")); strokeWidthSelector.setValue(UserConfig.getFloat(baseName + "StrokeWidth", 2) + ""); strokeWidthSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (isSettingValues || newValue == null || newValue.isEmpty()) { return; } try { float v = Float.parseFloat(newValue); if (v > 0) { UserConfig.setFloat(baseName + "StrokeWidth", v); ValidationTools.setEditorNormal(strokeWidthSelector); if (shapeController != null) { if (shapeController.shapeStyle != null) { shapeController.shapeStyle.setStrokeWidth(v); } shapeController.setMaskShapesStyle(); } } else { ValidationTools.setEditorBadStyle(strokeWidthSelector); } } catch (Exception e) { ValidationTools.setEditorBadStyle(strokeWidthSelector); } } }); strokeColorController.init(this, baseName + "StrokeColor", Color.web(ShapeStyle.DefaultStrokeColor)); strokeColorController.asSaved(); strokeColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (isSettingValues || shapeController == null) { return; } if (shapeController.shapeStyle != null) { shapeController.shapeStyle.setStrokeColor(strokeColorController.color()); } shapeController.setMaskShapesStyle(); } }); anchorSizeSelector.getItems().addAll(Arrays.asList("10", "2", "15", "1", "20", "3", "30", "4", "25", "5", "40", "50")); anchorSizeSelector.setValue(UserConfig.getFloat(baseName + "AnchorSize", 10) + ""); anchorSizeSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (isSettingValues || newValue == null || newValue.isEmpty()) { return; } try { float v = Float.parseFloat(newValue); if (v > 0) { UserConfig.setFloat(baseName + "AnchorSize", v); ValidationTools.setEditorNormal(anchorSizeSelector); if (shapeController != null) { if (shapeController.shapeStyle != null) { shapeController.shapeStyle.setAnchorSize(v); } shapeController.setMaskAnchorsStyle(); } } else { ValidationTools.setEditorBadStyle(anchorSizeSelector); } } catch (Exception e) { ValidationTools.setEditorBadStyle(anchorSizeSelector); } } }); anchorColorController.init(this, baseName + "AnchorColor", Color.web(ShapeStyle.DefaultAnchorColor)); anchorColorController.asSaved(); anchorColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (isSettingValues || shapeController == null) { return; } if (shapeController.shapeStyle != null) { shapeController.shapeStyle.setAnchorColor(anchorColorController.color()); } shapeController.setMaskAnchorsStyle(); } }); String anchorShape = UserConfig.getString(baseName + "AnchorShape", "Rectangle"); if ("Circle".equals(anchorShape)) { anchorCircleRadio.setSelected(true); if (shapeController != null) { shapeController.anchorShape = AnchorShape.Circle; } } else if ("Name".equals(anchorShape)) { anchorNameRadio.setSelected(true); if (shapeController != null) { shapeController.anchorShape = AnchorShape.Name; } } else { anchorRectRadio.setSelected(true); if (shapeController != null) { shapeController.anchorShape = AnchorShape.Rectangle; } } anchorShapeGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue v, Toggle oldValue, Toggle newValue) { if (isSettingValues) { return; } if (anchorCircleRadio.isSelected()) { UserConfig.setString(baseName + "AnchorShape", "Rectangle"); if (shapeController != null) { shapeController.anchorShape = AnchorShape.Circle; } } else if (anchorNameRadio.isSelected()) { UserConfig.setString(baseName + "AnchorShape", "Name"); if (shapeController != null) { shapeController.anchorShape = AnchorShape.Name; } } else { UserConfig.setString(baseName + "AnchorShape", "Rectangle"); if (shapeController != null) { shapeController.anchorShape = AnchorShape.Rectangle; } } if (shapeController != null) { shapeController.redrawMaskShape(); } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void setParameters(BaseShapeController parent, boolean withStroke) { try { super.setParameters(parent); shapeController = parent; if (!withStroke) { shapeBox.getChildren().remove(strokePane); } } catch (Exception e) { MyBoxLog.error(e); } } /* static methods */ public static ImageShapeOptionsController open(BaseShapeController parent, boolean withStroke) { try { if (parent == null) { return null; } ImageShapeOptionsController controller = (ImageShapeOptionsController) WindowTools.referredTopStage( parent, Fxmls.ImageShapeOptionsFxml); controller.setParameters(parent, withStroke); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImageMarginsBatchController.java
released/MyBox/src/main/java/mara/mybox/controller/ImageMarginsBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import javafx.beans.binding.Bindings; import javafx.fxml.FXML; import mara.mybox.image.tools.MarginTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-9-26 * @Description * @License Apache License Version 2.0 */ public class ImageMarginsBatchController extends BaseImageEditBatchController { @FXML protected ControlImageMargins marginsController; public ImageMarginsBatchController() { baseTitle = message("ImageBatch") + " - " + message("Margins"); } @Override public void initControls() { try { super.initControls(); marginsController.setParameters(null); startButton.disableProperty().unbind(); startButton.disableProperty().bind(Bindings.isEmpty(tableView.getItems()) .or(marginsController.widthSelector.getEditor().styleProperty().isEqualTo(UserConfig.badStyle())) .or(marginsController.distanceInput.styleProperty().isEqualTo(UserConfig.badStyle())) ); } catch (Exception e) { MyBoxLog.debug(e); } } @Override public boolean makeMoreParameters() { return super.makeMoreParameters() && marginsController.pickValues(); } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { try { BufferedImage target = null; if (marginsController.addRadio.isSelected()) { target = MarginTools.addMargins(currentTask, source, marginsController.colorController.awtColor(), marginsController.margin, marginsController.marginsTopCheck.isSelected(), marginsController.marginsBottomCheck.isSelected(), marginsController.marginsLeftCheck.isSelected(), marginsController.marginsRightCheck.isSelected()); } else if (marginsController.cutWidthRadio.isSelected()) { target = MarginTools.cutMarginsByColor(currentTask, source, marginsController.colorController.awtColor(), marginsController.marginsTopCheck.isSelected(), marginsController.marginsBottomCheck.isSelected(), marginsController.marginsLeftCheck.isSelected(), marginsController.marginsRightCheck.isSelected()); } else if (marginsController.cutColorRadio.isSelected()) { target = MarginTools.cutMarginsByWidth(currentTask, source, marginsController.margin, marginsController.marginsTopCheck.isSelected(), marginsController.marginsBottomCheck.isSelected(), marginsController.marginsLeftCheck.isSelected(), marginsController.marginsRightCheck.isSelected()); } else if (marginsController.blurRadio.isSelected()) { target = MarginTools.blurMarginsAlpha(currentTask, source, marginsController.margin, marginsController.marginsTopCheck.isSelected(), marginsController.marginsBottomCheck.isSelected(), marginsController.marginsLeftCheck.isSelected(), marginsController.marginsRightCheck.isSelected()); } return target; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ColorsManageController.java
released/MyBox/src/main/java/mara/mybox/controller/ColorsManageController.java
package mara.mybox.controller; import java.io.File; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioButton; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TableColumn; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Window; import mara.mybox.data.StringTable; import mara.mybox.db.data.ColorData; import mara.mybox.db.data.ColorDataTools; import mara.mybox.db.data.ColorPaletteName; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.data.VisitHistory.FileType; import mara.mybox.db.table.TableColor; import mara.mybox.db.table.TableColorPalette; import mara.mybox.db.table.TableColorPaletteName; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.cell.TableAutoCommitCell; import mara.mybox.fxml.cell.TableColorCell; import static mara.mybox.fxml.image.FxColorTools.color2css; import mara.mybox.fxml.image.PaletteTools; import mara.mybox.fxml.style.HtmlStyles; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2020-1-7 * @License Apache License Version 2.0 */ public class ColorsManageController extends BaseSysTableController<ColorData> { protected TableColorPaletteName tableColorPaletteName; protected TableColorPalette tableColorPalette; protected TableColor tableColor; @FXML protected ControlColorPaletteSelector palettesController; @FXML protected TableColumn<ColorData, Integer> colorValueColumn; @FXML protected TableColumn<ColorData, Color> colorColumn, invertColumn, complementaryColumn; @FXML protected TableColumn<ColorData, String> colorNameColumn, dataColumn, rgbaColumn, rgbColumn, hueColumn, rybColumn, saturationColumn, brightnessColumn, opacityColumn, sRGBColumn, HSBColumn, AdobeRGBColumn, AppleRGBColumn, ECIRGBColumn, sRGBLinearColumn, AdobeRGBLinearColumn, AppleRGBLinearColumn, CalculatedCMYKColumn, ECICMYKColumn, AdobeCMYKColumn, descColumn, XYZColumn, CIELabColumn, LCHabColumn, CIELuvColumn, LCHuvColumn, invertRGBColumn, complementaryRGBColumn; @FXML protected TableColumn<ColorData, Float> orderColumn; @FXML protected Button addColorsButton, customizeButton, trimButton; @FXML protected ToggleGroup showGroup; @FXML protected RadioButton colorsRadio, valuesRadio, allRadio, simpleMergedRadio, allMergedRadio; @FXML protected Label paletteLabel; @FXML protected TabPane paletteTabPane; @FXML protected Tab dataTab, colorsTab; @FXML protected ControlColorsPane colorsController; @FXML protected FlowPane buttonsPane; @FXML protected HtmlTableController infoController; @FXML protected VBox colorsBox; public ColorsManageController() { baseTitle = message("ManageColors"); TipsLabelKey = message("ColorsManageTips"); } @Override public void initValues() { try { super.initValues(); tableColorPaletteName = new TableColorPaletteName(); tableColorPalette = new TableColorPalette(); tableColor = new TableColor(); tableColorPalette.setTableColor(tableColor); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setFileType() { setFileType(VisitHistory.FileType.CSV); } @Override public void initControls() { try { super.initControls(); palettesController.setParameter(this, true); colorsController.setManager(this); palettesController.renamedNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { setTitle(baseTitle + " - " + palettesController.currentPaletteName()); paletteLabel.setText(palettesController.currentPaletteName()); } }); palettesController.selectedNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { refreshPalette(); } }); refreshPalettes(); infoController.initStyle(HtmlStyles.TableStyle); colorsController.clickNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { displayColorInfo(colorsController.clickedColor()); } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override protected void initColumns() { try { super.initColumns(); dataColumn.setPrefWidth(400); tableView.getColumns().remove(dataColumn); colorColumn.setCellValueFactory(new PropertyValueFactory<>("color")); colorColumn.setCellFactory(new TableColorCell<>()); invertColumn.setCellValueFactory(new PropertyValueFactory<>("invertColor")); invertColumn.setCellFactory(new TableColorCell<>()); invertRGBColumn.setCellValueFactory(new PropertyValueFactory<>("invertRGB")); complementaryColumn.setCellValueFactory(new PropertyValueFactory<>("complementaryColor")); complementaryColumn.setCellFactory(new TableColorCell<>()); complementaryRGBColumn.setCellValueFactory(new PropertyValueFactory<>("complementaryRGB")); colorValueColumn.setCellValueFactory(new PropertyValueFactory<>("colorValue")); orderColumn.setCellValueFactory(new PropertyValueFactory<>("orderNumner")); orderColumn.setCellFactory(TableAutoCommitCell.forFloatColumn()); orderColumn.setOnEditCommit((TableColumn.CellEditEvent<ColorData, Float> t) -> { if (t == null || palettesController.isAllColors()) { return; } ColorData row = t.getRowValue(); Float v = t.getNewValue(); if (row == null || v == null || v == row.getOrderNumner()) { return; } row.setOrderNumner(v); tableColorPalette.setOrder(palettesController.currentPaletteId(), row, v); refreshPalette(); }); orderColumn.getStyleClass().add("editable-column"); colorNameColumn.setCellValueFactory(new PropertyValueFactory<>("colorName")); colorNameColumn.setCellFactory(TableAutoCommitCell.forStringColumn()); colorNameColumn.setOnEditCommit((TableColumn.CellEditEvent<ColorData, String> t) -> { if (t == null) { return; } ColorData row = t.getRowValue(); if (row == null) { return; } String v = t.getNewValue(); String o = row.getColorName(); if (v == null && o == null || v != null && v.equals(o)) { return; } row.setColorName(v); if (palettesController.currentPalette != null) { tableColorPalette.setName(palettesController.currentPaletteId(), row, v); } else { tableColor.setName(row.getRgba(), v); } refreshPalette(); }); colorNameColumn.getStyleClass().add("editable-column"); rgbaColumn.setCellValueFactory(new PropertyValueFactory<>("rgba")); rgbColumn.setCellValueFactory(new PropertyValueFactory<>("rgb")); rybColumn.setCellValueFactory(new PropertyValueFactory<>("rybAngle")); hueColumn.setCellValueFactory(new PropertyValueFactory<>("hue")); saturationColumn.setCellValueFactory(new PropertyValueFactory<>("saturation")); brightnessColumn.setCellValueFactory(new PropertyValueFactory<>("brightness")); opacityColumn.setCellValueFactory(new PropertyValueFactory<>("opacity")); sRGBColumn.setCellValueFactory(new PropertyValueFactory<>("srgb")); HSBColumn.setCellValueFactory(new PropertyValueFactory<>("hsb")); AdobeRGBColumn.setCellValueFactory(new PropertyValueFactory<>("adobeRGB")); AppleRGBColumn.setCellValueFactory(new PropertyValueFactory<>("appleRGB")); ECIRGBColumn.setCellValueFactory(new PropertyValueFactory<>("eciRGB")); sRGBLinearColumn.setCellValueFactory(new PropertyValueFactory<>("SRGBLinear")); AdobeRGBLinearColumn.setCellValueFactory(new PropertyValueFactory<>("adobeRGBLinear")); AppleRGBLinearColumn.setCellValueFactory(new PropertyValueFactory<>("appleRGBLinear")); CalculatedCMYKColumn.setCellValueFactory(new PropertyValueFactory<>("calculatedCMYK")); ECICMYKColumn.setCellValueFactory(new PropertyValueFactory<>("eciCMYK")); AdobeCMYKColumn.setCellValueFactory(new PropertyValueFactory<>("adobeCMYK")); XYZColumn.setCellValueFactory(new PropertyValueFactory<>("xyz")); CIELabColumn.setCellValueFactory(new PropertyValueFactory<>("cieLab")); LCHabColumn.setCellValueFactory(new PropertyValueFactory<>("lchab")); CIELuvColumn.setCellValueFactory(new PropertyValueFactory<>("cieLuv")); LCHuvColumn.setCellValueFactory(new PropertyValueFactory<>("lchuv")); descColumn.setCellValueFactory(new PropertyValueFactory<>("description")); } catch (Exception e) { MyBoxLog.error(e); } } @Override protected void initButtons() { try { super.initButtons(); exportButton.disableProperty().bind(Bindings.isEmpty(tableData)); showGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { checkColumns(); loadTableData(); } }); checkColumns(); } catch (Exception e) { MyBoxLog.error(e); } } protected void checkColumns() { try { isSettingValues = true; tableView.getColumns().clear(); tableView.getColumns().addAll(rowsSelectionColumn, colorColumn, colorNameColumn); if (!palettesController.isAllColors()) { tableView.getColumns().add(orderColumn); } if (simpleMergedRadio.isSelected()) { dataColumn.setCellValueFactory(new PropertyValueFactory<>("colorSimpleDisplay")); tableView.getColumns().addAll(rgbaColumn, rgbColumn, dataColumn, invertColumn, invertRGBColumn, complementaryColumn, complementaryRGBColumn); } else if (allMergedRadio.isSelected()) { dataColumn.setCellValueFactory(new PropertyValueFactory<>("colorDisplay")); tableView.getColumns().addAll(rgbaColumn, rgbColumn, dataColumn, invertColumn, invertRGBColumn, complementaryColumn, complementaryRGBColumn); } else if (valuesRadio.isSelected()) { tableView.getColumns().addAll(rgbaColumn, rgbColumn, rybColumn, hueColumn, saturationColumn, brightnessColumn, opacityColumn, HSBColumn, sRGBColumn, CalculatedCMYKColumn, invertColumn, invertRGBColumn, complementaryColumn, complementaryRGBColumn, colorValueColumn); } else if (allRadio.isSelected()) { tableView.getColumns().addAll(rgbaColumn, rgbColumn, rybColumn, hueColumn, saturationColumn, brightnessColumn, opacityColumn, HSBColumn, sRGBColumn, CalculatedCMYKColumn, invertColumn, invertRGBColumn, complementaryColumn, complementaryRGBColumn, AdobeRGBColumn, AppleRGBColumn, ECIRGBColumn, sRGBLinearColumn, AdobeRGBLinearColumn, AppleRGBLinearColumn, ECICMYKColumn, AdobeCMYKColumn, XYZColumn, CIELabColumn, LCHabColumn, CIELuvColumn, LCHuvColumn, colorValueColumn); } else { tableView.getColumns().addAll(rybColumn, hueColumn, saturationColumn, brightnessColumn, opacityColumn, invertColumn, invertRGBColumn, complementaryColumn, complementaryRGBColumn, HSBColumn, rgbaColumn, rgbColumn); } isSettingValues = false; } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(addColorsButton, message("AddColors")); NodeStyleTools.setTooltip(trimButton, message("TrimOrderInPalette")); NodeStyleTools.setTooltip(customizeButton, message("CustomizeColors")); } catch (Exception e) { MyBoxLog.debug(e); } } /* palettes list */ public void refreshPalettes() { palettesController.loadPalettes(); } /* Palette */ public void refreshPalette() { trimButton.setDisable(palettesController.isAllColors()); setTitle(baseTitle + " - " + palettesController.currentPaletteName()); paletteLabel.setText(palettesController.currentPaletteName()); checkColumns(); loadTableData(); } public void loadPaletteLast(ColorPaletteName palette) { loadPalette(palette != null ? palette.getName() : null); } public void loadPalette(String paletteName) { pagination.currentPage = Integer.MAX_VALUE; palettesController.loadPalette(paletteName); paletteTabPane.getSelectionModel().select(colorsTab); } @FXML @Override public void addAction() { ColorsInputController.oneOpen(this); } @FXML protected void showExportMenu(Event event) { try { List<MenuItem> items = new ArrayList<>(); MenuItem menu = new MenuItem(message("ExportAllData") + " - CSV"); menu.setOnAction((ActionEvent e) -> { exportCSV("all"); }); items.add(menu); menu = new MenuItem(message("ExportCurrentPage") + " - CSV"); menu.setOnAction((ActionEvent e) -> { exportCSV("page"); }); items.add(menu); menu = new MenuItem(message("ExportSelectedData") + " - CSV"); menu.setOnAction((ActionEvent e) -> { exportCSV("selected"); }); items.add(menu); items.add(new SeparatorMenuItem()); menu = new MenuItem(message("ExportAllData") + " - Html"); menu.setOnAction((ActionEvent e) -> { exportHtml("all"); }); items.add(menu); menu = new MenuItem(message("ExportCurrentPage") + " - Html"); menu.setOnAction((ActionEvent e) -> { exportHtml("page"); }); items.add(menu); menu = new MenuItem(message("ExportSelectedData") + " - Html"); menu.setOnAction((ActionEvent e) -> { exportHtml("selected"); }); items.add(menu); items.add(new SeparatorMenuItem()); items.add(MenuTools.popCheckMenu("ColorExport")); popEventMenu(event, items); } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void popExportMenu(Event event) { if (MenuTools.isPopMenu("ColorExport", false)) { showExportMenu(event); } } public void exportCSV(String type) { if (task != null && !task.isQuit()) { return; } final List<ColorData> rows; boolean isAll = palettesController.isAllColors(); String filename = palettesController.currentPaletteName(); if ("selected".equals(type)) { rows = selectedItems(); if (rows == null || rows.isEmpty()) { popError(message("NoData")); return; } filename += "_" + message("Selected"); } else { rows = tableData; if (rows == null || rows.isEmpty()) { popError(message("NoData")); return; } if ("page".equals(type)) { filename += "_" + message("Page") + (pagination.currentPage + 1); } else { filename += "_" + message("All"); } } final File file = saveCurrentFile(FileType.CSV, filename + ".csv"); if (file == null) { return; } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { if ("all".equals(type)) { if (isAll) { ColorDataTools.exportCSV(tableColor, file); } else { ColorDataTools.exportCSV(tableColorPalette, file, palettesController.currentPalette()); } } else { ColorDataTools.exportCSV(rows, file, !isAll); } return true; } @Override protected void whenSucceeded() { if (file.exists()) { recordFileWritten(file, FileType.Text); Data2DManufactureController.openCSVFile(file); } } }; start(task); } public void exportHtml(String type) { try { List<ColorData> rows; boolean isAll = palettesController.isAllColors(); String title = palettesController.currentPaletteName(); if ("selected".equals(type)) { rows = selectedItems(); if (rows == null || rows.isEmpty()) { popError(message("NoData")); return; } title += "_" + message("Selected"); displayHtml(title, rows); } else { rows = tableData; if (rows == null || rows.isEmpty()) { popError(message("NoData")); return; } if ("page".equals(type)) { title += "_" + message("Page") + (pagination.currentPage + 1); displayHtml(title, rows); } else { String atitle = title; if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { private List<ColorData> data; @Override protected boolean handle() { if (isAll) { data = tableColor.readAll(); } else { data = tableColorPalette.colors(palettesController.currentPaletteId()); } return data != null; } @Override protected void whenSucceeded() { displayHtml(atitle, data); } }; start(task); } } } catch (Exception e) { MyBoxLog.error(e); } } public void displayHtml(String title, List<ColorData> rows) { try { if (rows == null || rows.isEmpty()) { popError(message("NoData")); return; } List<String> names = new ArrayList<>(); for (TableColumn column : tableView.getColumns()) { if (!column.equals(rowsSelectionColumn) && !column.equals(orderColumn)) { names.add(column.getText()); } } StringTable table = new StringTable(names, title); for (ColorData data : rows) { if (data.needConvert()) { data.convert(); } List<String> row = new ArrayList<>(); for (TableColumn column : tableView.getColumns()) { if (column.equals(colorValueColumn)) { row.add(data.getColorValue() + ""); } else if (column.equals(colorColumn)) { row.add("<DIV style=\"width: 50px; " + "background-color:" + color2css(data.getColor()) + "; \">" + "&nbsp;&nbsp;&nbsp;</DIV>"); } else if (column.equals(colorNameColumn)) { row.add(data.getColorName()); } else if (column.equals(rgbaColumn)) { row.add(data.getRgba()); } else if (column.equals(rgbColumn)) { row.add(data.getRgb()); } else if (column.equals(sRGBColumn)) { row.add(data.getSrgb()); } else if (column.equals(HSBColumn)) { row.add(data.getHsb()); } else if (column.equals(hueColumn)) { row.add(data.getHue()); } else if (column.equals(saturationColumn)) { row.add(data.getSaturation()); } else if (column.equals(brightnessColumn)) { row.add(data.getBrightness()); } else if (column.equals(rybColumn)) { row.add(data.getRybAngle()); } else if (column.equals(opacityColumn)) { row.add(data.getOpacity()); } else if (column.equals(AdobeRGBColumn)) { row.add(data.getAdobeRGB()); } else if (column.equals(AppleRGBColumn)) { row.add(data.getAppleRGB()); } else if (column.equals(ECIRGBColumn)) { row.add(data.getEciRGB()); } else if (column.equals(sRGBLinearColumn)) { row.add(data.getSRGBLinear()); } else if (column.equals(AdobeRGBLinearColumn)) { row.add(data.getAdobeRGBLinear()); } else if (column.equals(AppleRGBLinearColumn)) { row.add(data.getAppleRGBLinear()); } else if (column.equals(CalculatedCMYKColumn)) { row.add(data.getCalculatedCMYK()); } else if (column.equals(ECICMYKColumn)) { row.add(data.getEciCMYK()); } else if (column.equals(AdobeCMYKColumn)) { row.add(data.getAdobeCMYK()); } else if (column.equals(XYZColumn)) { row.add(data.getXyz()); } else if (column.equals(CIELabColumn)) { row.add(data.getCieLab()); } else if (column.equals(LCHabColumn)) { row.add(data.getLchab()); } else if (column.equals(CIELuvColumn)) { row.add(data.getCieLuv()); } else if (column.equals(LCHuvColumn)) { row.add(data.getLchuv()); } else if (column.equals(dataColumn)) { if (allMergedRadio.isSelected()) { row.add(ColorData.htmlValue(data)); } else { row.add(ColorData.htmlSimpleValue(data)); } } else if (column.equals(invertColumn)) { row.add("<DIV style=\"width: 50px; " + "background-color:" + color2css(data.getInvertColor()) + "; \">" + "&nbsp;&nbsp;&nbsp;</DIV>"); } else if (column.equals(invertRGBColumn)) { row.add(data.getInvertRGB()); } else if (column.equals(complementaryColumn)) { row.add("<DIV style=\"width: 50px; " + " background-color:" + color2css(data.getComplementaryColor()) + "; \">" + "&nbsp;&nbsp;&nbsp;</DIV>"); } else if (column.equals(complementaryRGBColumn)) { row.add(data.getComplementaryRGB()); } } table.add(row); } String html = HtmlWriteTools.html(title, HtmlStyles.styleValue("Table"), table.body()); WebBrowserController.openHtml(html, HtmlStyles.styleValue("Table"), true); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void sourceFileChanged(File file) { PaletteTools.importFile(this, file, palettesController.currentPaletteName(), false); } @FXML @Override public void deleteAction() { if (paletteTabPane.getSelectionModel().getSelectedItem() == dataTab) { super.deleteAction(); return; } if (colorsController.clickedRect == null) { return; } if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { private int deletedCount = 0; @Override protected boolean handle() { deletedCount = tableColorPalette.delete(colorsController.clickedColor()); return deletedCount >= 0; } @Override protected void whenSucceeded() { popInformation(message("Deleted") + ":" + deletedCount); if (deletedCount > 0) { afterDeletion(); } } }; start(task); } @Override protected long clearData(FxTask currentTask) { if (palettesController.isAllColors()) { return tableColor.clearData(); } else { return tableColorPalette.clear(palettesController.currentPaletteId()); } } @Override public void resetView(boolean changed) { super.resetView(changed); colorsController.colorsPane.getChildren().clear(); infoController.clear(); } @FXML protected void trimAction() { if (palettesController.isAllColors()) { return; } if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { return tableColorPalette.trim(palettesController.currentPaletteId()); } @Override protected void whenSucceeded() { refreshPalette(); } }; start(task); } @FXML public void queryAction() { openStage(Fxmls.ColorQueryFxml); } @FXML public void customizePalette() { ColorsCustomizeController.open(this); } /* Data */ @Override public long readDataSize(FxTask currentTask, Connection conn) { long size; if (palettesController.isAllColors()) { size = tableColor.size(conn); } else { size = tableColorPalette.size(conn, palettesController.currentPaletteId()); } dataSizeLoaded = true; return size; } @Override public List<ColorData> readPageData(FxTask currentTask, Connection conn) { if (palettesController.isAllColors()) { return tableColor.queryConditions(conn, null, null, pagination.startRowOfCurrentPage, pagination.pageSize); } else { return tableColorPalette.colors(conn, palettesController.currentPaletteId(), pagination.startRowOfCurrentPage, pagination.pageSize); } } @Override public void postLoadedTableData() { super.postLoadedTableData(); colorsController.loadColors(palettesController.currentPalette(), tableData); } @Override protected int deleteData(FxTask currentTask, List<ColorData> data) { if (data == null || data.isEmpty()) { return 0; } if (palettesController.isAllColors()) { return tableColor.deleteData(data); } else { return tableColorPalette.delete(data); } } @FXML @Override public void refreshAction() { refreshPalette(); } @Override protected void checkSelected() { if (isSettingValues) { return; } super.checkSelected(); ColorData color = selectedItem(); copyButton.setDisable(color == null); displayColorInfo(color); } protected void displayColorInfo(ColorData color) { if (color == null) { return; } infoController.displayHtml(color.html()); } @Override protected void checkButtons() { if (isSettingValues) { return; } super.checkButtons(); popButton.setDisable(isNoneSelected()); } @FXML @Override public void copyAction() { ColorCopyController controller = (ColorCopyController) openStage(Fxmls.ColorCopyFxml); controller.setParameters(this); controller.requestMouse(); } @Override public void doubleClicked(Event event) { popAction(); } @FXML @Override public boolean popAction() { ColorData selected = tableView.getSelectionModel().getSelectedItem(); if (selected == null) { return false; } HtmlPopController.showHtml(this, selected.html()); return true; } @FXML protected void popHelps(Event event) { if (UserConfig.getBoolean("ColorHelpsPopWhenMouseHovering", false)) { showHelps(event); } } @FXML protected void showHelps(Event event) { popEventMenu(event, HelpTools.colorHelps(true)); } /* static methods */ public static ColorsManageController oneOpen() { ColorsManageController controller = null; List<Window> windows = new ArrayList<>(); windows.addAll(Window.getWindows()); for (Window window : windows) { Object object = window.getUserData(); if (object != null && object instanceof ColorsManageController) { try { controller = (ColorsManageController) object; break; } catch (Exception e) { } } } if (controller == null) { controller = (ColorsManageController) WindowTools.openStage(Fxmls.ColorsManageFxml); } controller.requestMouse();
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlSynchronizeOptions.java
released/MyBox/src/main/java/mara/mybox/controller/ControlSynchronizeOptions.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.DatePicker; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.VBox; import mara.mybox.data.FileSynchronizeAttributes; import mara.mybox.db.table.TableStringValues; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.tools.DateTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.TimeFormats; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-7-8 * @License Apache License Version 2.0 */ public class ControlSynchronizeOptions extends BaseController { protected FileSynchronizeAttributes copyAttr; @FXML protected VBox conditionsBox; @FXML protected TextField notCopyInput, permissionInput; @FXML protected ToggleGroup copyGroup; @FXML protected RadioButton conditionallyRadio; @FXML protected CheckBox copySubdirCheck, copyEmptyCheck, copyNewCheck, copyHiddenCheck, copyReadonlyCheck, copyExistedCheck, copyModifiedCheck, deleteNonExistedCheck, notCopyCheck, copyAttrCheck, copyMtimeCheck, permissionCheck, deleteSourceCheck, errorContinueCheck; @FXML protected DatePicker modifyAfterInput; public ControlSynchronizeOptions() { baseTitle = message("DirectorySynchronize"); } public void setParameters(BaseController parent) { try { this.parentController = parent; this.baseName = parent.baseName; setControls(); } catch (Exception e) { MyBoxLog.debug(e); } } private void setControls() { try { conditionsBox.disableProperty().bind(conditionallyRadio.selectedProperty().not()); copySubdirCheck.setSelected(UserConfig.getBoolean(baseName + "CopySubdir", true)); copySubdirCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopySubdir", nv); } }); copyEmptyCheck.setSelected(UserConfig.getBoolean(baseName + "CopyEmpty", true)); copyEmptyCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopyEmpty", nv); } }); copyNewCheck.setSelected(UserConfig.getBoolean(baseName + "CopyNew", true)); copyNewCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopyNew", nv); } }); copyHiddenCheck.setSelected(UserConfig.getBoolean(baseName + "CopyHidden", true)); copyHiddenCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopyHidden", nv); } }); copyReadonlyCheck.setSelected(UserConfig.getBoolean(baseName + "CopyReadonly", false)); copyReadonlyCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopyReadonly", nv); } }); copyExistedCheck.setSelected(UserConfig.getBoolean(baseName + "CopyExisted", true)); copyExistedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopyExisted", nv); } }); copyModifiedCheck.setSelected(UserConfig.getBoolean(baseName + "CopyModified", true)); copyModifiedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopyModified", nv); } }); deleteNonExistedCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (deleteNonExistedCheck.isSelected()) { deleteNonExistedCheck.setStyle(NodeStyleTools.darkRedTextStyle()); } else { deleteNonExistedCheck.setStyle(null); } UserConfig.setBoolean(baseName + "DeleteNonExisted", nv); } }); deleteNonExistedCheck.setSelected(UserConfig.getBoolean(baseName + "DeleteNonExisted", false)); notCopyCheck.setSelected(UserConfig.getBoolean(baseName + "NotCopy", false)); notCopyCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "NotCopy", nv); } }); if (copyAttrCheck != null) { copyAttrCheck.setSelected(UserConfig.getBoolean(baseName + "CopyAttr", true)); copyAttrCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopyAttr", nv); } }); } if (copyMtimeCheck != null) { copyMtimeCheck.setSelected(UserConfig.getBoolean(baseName + "CopyMtime", true)); copyMtimeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "CopyMtime", nv); } }); } if (permissionCheck != null) { permissionCheck.setSelected(UserConfig.getBoolean(baseName + "SetPermissions", false)); permissionCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setBoolean(baseName + "SetPermissions", nv); } }); } if (permissionInput != null) { permissionInput.setText(UserConfig.getString(baseName + "Permissions", "755")); } deleteSourceCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (deleteSourceCheck.isSelected()) { deleteSourceCheck.setStyle(NodeStyleTools.darkRedTextStyle()); } else { deleteSourceCheck.setStyle(null); } UserConfig.setBoolean(baseName + "DeleteSource", nv); } }); deleteSourceCheck.setSelected(UserConfig.getBoolean(baseName + "DeleteSource", false)); if (errorContinueCheck != null) { errorContinueCheck.setSelected(false); errorContinueCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (errorContinueCheck.isSelected()) { errorContinueCheck.setStyle(NodeStyleTools.darkRedTextStyle()); } else { errorContinueCheck.setStyle(null); } } }); } } catch (Exception e) { MyBoxLog.debug(e); } } protected FileSynchronizeAttributes pickOptions() { try { copyAttr = new FileSynchronizeAttributes(); copyAttr.setCopyEmpty(copyEmptyCheck.isSelected()); copyAttr.setConditionalCopy(conditionallyRadio.isSelected()); copyAttr.setCopyExisted(copyExistedCheck.isSelected()); copyAttr.setCopyHidden(copyHiddenCheck.isSelected()); copyAttr.setCopyNew(copyNewCheck.isSelected()); copyAttr.setCopySubdir(copySubdirCheck.isSelected()); copyAttr.setNotCopySome(notCopyCheck.isSelected()); copyAttr.setOnlyCopyReadonly(copyReadonlyCheck.isSelected()); List<String> notCopy = new ArrayList<>(); String inputs = notCopyInput.getText(); if (copyAttr.isNotCopySome() && inputs != null && !inputs.isBlank()) { List<String> values = Arrays.asList(inputs.trim().split(",")); notCopy.addAll(values); TableStringValues.add(interfaceName + "Histories", values); } copyAttr.setNotCopyNames(notCopy); copyAttr.setOnlyCopyModified(copyModifiedCheck.isSelected()); if (copyAttr.isOnlyCopyModified() && modifyAfterInput.getValue() != null) { Date d = DateTools.localDateToDate(modifyAfterInput.getValue()); copyAttr.setModifyAfter(d.getTime()); TableStringValues.add(interfaceName + "Modify", DateTools.datetimeToString(d, TimeFormats.DateC)); } else { copyAttr.setModifyAfter(-Long.MAX_VALUE); } copyAttr.setContinueWhenError(errorContinueCheck.isSelected()); copyAttr.setCopyAttrinutes(copyAttrCheck != null ? copyAttrCheck.isSelected() : true); copyAttr.setCopyMTime(copyMtimeCheck != null ? copyMtimeCheck.isSelected() : true); copyAttr.setSetPermissions(permissionCheck != null ? permissionCheck.isSelected() : false); copyAttr.setPermissions(-1); if (copyAttr.isSetPermissions() && permissionInput != null) { try { int v = Integer.parseInt(permissionInput.getText(), 8); copyAttr.setPermissions(v); UserConfig.setString(baseName + "Permissions", permissionInput.getText()); } catch (Exception e) { popError(message("InvalidParameter") + ": " + message("Permissions")); return null; } } copyAttr.setDeleteNotExisteds(deleteNonExistedCheck.isSelected()); if (!copyAttr.isCopyNew() && !copyAttr.isCopyExisted() && !copyAttr.isCopySubdir()) { alertInformation(message("NothingCopy")); return null; } return copyAttr; } catch (Exception e) { MyBoxLog.error(e); return null; } } @FXML protected void popNameHistories(Event event) { if (UserConfig.getBoolean(interfaceName + "HistoriesPopWhenMouseHovering", false)) { showNameHistories(event); } } @FXML protected void showNameHistories(Event event) { PopTools.popSavedValues(this, notCopyInput, event, interfaceName + "Histories", true); } @FXML protected void popModifyHistories(Event event) { if (UserConfig.getBoolean(interfaceName + "ModifyPopWhenMouseHovering", false)) { showModifyHistories(event); } } @FXML protected void showModifyHistories(Event event) { PopTools.popSavedValues(this, modifyAfterInput.getEditor(), event, interfaceName + "Modify", true); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/RemotePathManageController.java
released/MyBox/src/main/java/mara/mybox/controller/RemotePathManageController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.Tab; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.cell.TreeItemPropertyValueFactory; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.VBox; import mara.mybox.data.FileNode; import mara.mybox.data.RemoteFile; import mara.mybox.db.data.PathConnection; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.TextClipboardTools; import mara.mybox.fxml.WindowTools; import static mara.mybox.fxml.style.NodeStyleTools.attributeTextStyle; import mara.mybox.fxml.style.StyleTools; import mara.mybox.tools.StringTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-3-18 * @License Apache License Version 2.0 */ public class RemotePathManageController extends FilesTreeController { protected ChangeListener<Boolean> expandListener; @FXML protected ControlRemoteConnection remoteController; @FXML protected Tab remoteTab, filesTab; @FXML protected VBox filesBox; @FXML protected TreeTableColumn<FileNode, Integer> uidColumn, gidColumn; @FXML protected Button clearDirectoryButton, permissionButton, makeDirectoryButton, downloadButton, uploadButton; public RemotePathManageController() { baseTitle = message("RemotePathManage"); listenDoubleClick = false; } @Override public void initControls() { try { super.initControls(); remoteController.setParameters(this); filesBox.setDisable(true); uidColumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("uid")); gidColumn.setCellValueFactory(new TreeItemPropertyValueFactory<>("gid")); filesTreeView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (popMenu != null && popMenu.isShowing()) { popMenu.hide(); } if (event.getButton() == MouseButton.SECONDARY) { showFunctionsMenu(event); } } }); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void startAction() { goPath(); } @FXML public void goPath() { filesBox.setDisable(true); if (!remoteController.pickProfile()) { return; } remoteController.disconnect(); loadPath(); } public void loadPath() { if (task != null) { task.cancel(); } tabPane.getSelectionModel().select(logsTab); task = new FxSingletonTask<Void>(this) { TreeItem<FileNode> rootItem; @Override protected boolean handle() { try { if (!checkConnection()) { return false; } String rootPath = remoteController.currentConnection.getPath(); FileNode rootInfo = new RemoteFile(remoteController.stat(rootPath)) .setNodename(rootPath); rootItem = new TreeItem(rootInfo); rootItem.setExpanded(true); List<TreeItem<FileNode>> children = makeChildren(this, rootItem); if (children != null && !children.isEmpty()) { rootItem.getChildren().setAll(children); addSelectedListener(rootItem); } return true; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { } @Override protected void whenCanceled() { taskCancelled = true; showLogs(message("Cancel")); } @Override protected void finalAction() { super.finalAction(); tabPane.getSelectionModel().select(filesTab); filesBox.setDisable(false); filesTreeView.setRoot(rootItem); } }; start(task); } protected boolean checkConnection() { remoteController.task = task; if (remoteController.sshSession != null && remoteController.sshSession.isConnected()) { return true; } return remoteController.connect(task); } protected List<TreeItem<FileNode>> makeChildren(FxTask currentTask, TreeItem<FileNode> treeItem) { List<TreeItem<FileNode>> children = new ArrayList<>(); try { FileNode remoteFile = (FileNode) (treeItem.getValue()); if (remoteFile == null || !checkConnection()) { return null; } List<FileNode> fileNodes = remoteController.children(currentTask, remoteFile); if (currentTask == null || !currentTask.isWorking()) { return null; } if (fileNodes == null || fileNodes.isEmpty()) { return children; } Collections.sort(fileNodes, new Comparator<FileNode>() { @Override public int compare(FileNode v1, FileNode v2) { if (v1.isDirectory()) { if (!v2.isDirectory()) { return -1; } } else { if (v2.isDirectory()) { return 1; } } return v1.getFullName().compareTo(v2.getFullName()); } }); for (FileNode fileInfo : fileNodes) { TreeItem<FileNode> fileItem = new TreeItem<>(fileInfo); fileItem.setExpanded(true); children.add(fileItem); if (fileInfo.isDirectory()) { FileNode dummyInfo = new FileNode() .setNodename("Loading") .setParentFile(remoteFile); TreeItem<FileNode> dummyItem = new TreeItem(dummyInfo); fileItem.getChildren().add(dummyItem); fileItem.setExpanded(false); fileItem.expandedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (!isSettingValues) { fileItem.expandedProperty().removeListener(this); expandPath(fileItem); } } }); } } } catch (Exception e) { error = e.toString(); } return children; } protected void expandPath(TreeItem<FileNode> treeItem) { if (treeItem == null) { return; } FileNode remoteFile = (FileNode) (treeItem.getValue()); if (remoteFile == null) { return; } if (task != null) { task.cancel(); } treeItem.setExpanded(true); task = new FxSingletonTask<Void>(this) { List<TreeItem<FileNode>> children; @Override protected boolean handle() { try { children = makeChildren(this, treeItem); return children != null; } catch (Exception e) { error = e.toString(); return true; } } @Override protected void whenSucceeded() { } @Override protected void whenCanceled() { taskCancelled = true; showLogs(message("Cancel")); } @Override protected void finalAction() { super.finalAction(); tabPane.getSelectionModel().select(filesTab); treeItem.getChildren().setAll(children); if (!children.isEmpty()) { addSelectedListener(treeItem); } } }; start(task); } @FXML public void disconnect() { tabPane.getSelectionModel().select(logsTab); if (task != null) { task.cancel(); } remoteController.disconnect(); popInformation(message("Disconnected")); } @FXML @Override public void refreshAction() { loadPath(); } @FXML public void copyFileNameAction() { TreeItem<FileNode> item = filesTreeView.getSelectionModel().getSelectedItem(); if (item == null) { popError(message("SelectToHandle")); return; } TextClipboardTools.copyToSystemClipboard(this, item.getValue().getNodename()); } @FXML public void copyFullNameAction() { TreeItem<FileNode> item = filesTreeView.getSelectionModel().getSelectedItem(); if (item == null) { popError(message("SelectToHandle")); return; } TextClipboardTools.copyToSystemClipboard(this, item.getValue().nodeFullName()); } @FXML public void renameAction() { RemotePathRenameController.open(this); } public void renameFile(String currentName, String newName) { if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { if (!checkConnection()) { return false; } return remoteController.renameFile(currentName, newName); } @Override protected void whenCanceled() { taskCancelled = true; showLogs(message("Cancel")); disconnect(); } @Override protected void finalAction() { super.finalAction(); loadPath(); } }; start(task); } @FXML public void getAction() { RemotePathGetController.open(this); } @FXML public void putAction() { RemotePathPutController.open(this); } @FXML public void makeDirectory() { TreeItem<FileNode> item = filesTreeView.getSelectionModel().getSelectedItem(); if (item == null) { item = filesTreeView.getRoot(); } String makeName = PopTools.askValue(baseTitle, message("CreateFileComments"), message("MakeDirectory"), item.getValue().path(true) + "m"); if (makeName == null || makeName.isBlank()) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { if (!checkConnection()) { return false; } return remoteController.mkdirs(makeName); } @Override protected void whenCanceled() { taskCancelled = true; showLogs(message("Cancel")); disconnect(); } @Override protected void finalAction() { super.finalAction(); loadPath(); } }; start(task); } @FXML public void permissionAction() { RemotePathPermissionController.open(this); } @FXML @Override public void deleteAction() { RemotePathDeleteController.open(this); } @FXML public void clearDirectory() { TreeItem<FileNode> item = filesTreeView.getSelectionModel().getSelectedItem(); if (item == null) { popError(message("SelectToHandle")); return; } String filename = item.getValue().path(false); String clearName = PopTools.askValue(baseTitle, message("MakeSureAccountHasPermission"), message("ClearDirectory"), filename); if (clearName == null || clearName.isBlank()) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { if (!checkConnection()) { return false; } remoteController.count = 0; return remoteController.clearDirectory(this, clearName); } @Override protected void whenCanceled() { taskCancelled = true; showLogs(message("Cancel")); disconnect(); } @Override protected void finalAction() { super.finalAction(); showLogs(message("Deleted") + ": " + remoteController.count); loadPath(); } }; start(task); } public void showFunctionsMenu(MouseEvent event) { if (getMyWindow() == null) { return; } TreeItem<FileNode> item = filesTreeView.getSelectionModel().getSelectedItem(); String filename; if (item == null || item.getValue() == null) { filename = null; } else if (item.getValue().isDirectory()) { filename = StringTools.menuSuffix(item.getValue().nodeFullName()); } else { filename = (StringTools.menuSuffix(item.getValue().path(true)) + "\n" + StringTools.menuSuffix(item.getValue().getNodename())); } List<MenuItem> items = new ArrayList<>(); MenuItem menuItem = new MenuItem(filename); menuItem.setStyle(attributeTextStyle()); items.add(menuItem); items.add(new SeparatorMenuItem()); menuItem = new MenuItem(message("Download"), StyleTools.getIconImageView("iconDownload.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { getAction(); }); items.add(menuItem); menuItem = new MenuItem(message("CopyFileName"), StyleTools.getIconImageView("iconCopySystem.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { copyFileNameAction(); }); menuItem.setDisable(item == null); items.add(menuItem); menuItem = new MenuItem(message("CopyFullName"), StyleTools.getIconImageView("iconCopySystem.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { copyFullNameAction(); }); menuItem.setDisable(item == null); items.add(menuItem); menuItem = new MenuItem(message("Refresh"), StyleTools.getIconImageView("iconRefresh.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { refreshAction(); }); items.add(menuItem); items.add(new SeparatorMenuItem()); menuItem = new MenuItem(message("MakeDirectory"), StyleTools.getIconImageView("iconNewItem.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { makeDirectory(); }); items.add(menuItem); menuItem = new MenuItem(message("Upload"), StyleTools.getIconImageView("iconUpload.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { putAction(); }); items.add(menuItem); menuItem = new MenuItem(message("Delete"), StyleTools.getIconImageView("iconDelete.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { deleteAction(); }); items.add(menuItem); menuItem = new MenuItem(message("ClearDirectory"), StyleTools.getIconImageView("iconClear.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { clearDirectory(); }); items.add(menuItem); menuItem = new MenuItem(message("Rename"), StyleTools.getIconImageView("iconInput.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { renameAction(); }); items.add(menuItem); menuItem = new MenuItem(message("SetPermissions"), StyleTools.getIconImageView("iconPermission.png")); menuItem.setOnAction((ActionEvent menuItemEvent) -> { permissionAction(); }); items.add(menuItem); items.add(new SeparatorMenuItem()); popEventMenu(event, items); } public void openPath(PathConnection profile) { remoteController.editProfile(profile); goPath(); } @Override public void cleanPane() { try { cancelTask(); taskCancelled = true; remoteController.disconnect(); } catch (Exception e) { } super.cleanPane(); } /* static methods */ public static RemotePathManageController open(PathConnection profile) { try { RemotePathManageController controller = (RemotePathManageController) WindowTools.openStage(Fxmls.RemotePathManageFxml); controller.requestMouse(); controller.openPath(profile); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/FilesCopyController.java
released/MyBox/src/main/java/mara/mybox/controller/FilesCopyController.java
package mara.mybox.controller; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2019-10-13 * @License Apache License Version 2.0 */ public class FilesCopyController extends BaseBatchFileController { @FXML protected CheckBox copyAttrCheck; public FilesCopyController() { baseTitle = Languages.message("FilesCopy"); } @Override public String handleFile(FxTask currentTask, File srcFile, File targetPath) { try { File target = makeTargetFile(srcFile, targetPath); if (target == null) { return Languages.message("Skip"); } Path path; if (copyAttrCheck.isSelected()) { path = Files.copy(Paths.get(srcFile.getAbsolutePath()), Paths.get(target.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } else { path = Files.copy(Paths.get(srcFile.getAbsolutePath()), Paths.get(target.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); } if (path == null) { return Languages.message("Failed"); } targetFileGenerated(target); return Languages.message("Successful"); } catch (Exception e) { MyBoxLog.error(e); return Languages.message("Failed"); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/SvgCubicController.java
released/MyBox/src/main/java/mara/mybox/controller/SvgCubicController.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.control.TreeItem; import mara.mybox.data.XmlTreeNode; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import org.w3c.dom.Element; /** * @Author Mara * @CreateDate 2023-12-29 * @License Apache License Version 2.0 */ public class SvgCubicController extends BaseSvgShapeController { @FXML protected ControlCubic cubicController; @Override public void initMore() { try { shapeName = message("CubicCurve"); cubicController.setParameters(this); anchorCheck.setSelected(true); showAnchors = true; popShapeMenu = true; } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean elementToShape(Element node) { return false; } @Override public void showShape() { showMaskCubic(); } @Override public void setShapeInputs() { cubicController.loadValues(); } @Override public boolean shape2Element() { try { if (maskCubicData == null) { return false; } if (shapeElement == null) { shapeElement = doc.createElement("path"); } shapeElement.setAttribute("d", maskCubicData.pathAbs()); return true; } catch (Exception e) { MyBoxLog.error(e); } return false; } @Override public boolean pickShape() { return cubicController.pickValues(); } /* static */ public static SvgCubicController drawShape(SvgEditorController editor, TreeItem<XmlTreeNode> item, Element element) { try { if (editor == null || item == null) { return null; } SvgCubicController controller = (SvgCubicController) WindowTools.childStage( editor, Fxmls.SvgCubicFxml); controller.setParameters(editor, item, element); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/TextInMyBoxClipboardController.java
released/MyBox/src/main/java/mara/mybox/controller/TextInMyBoxClipboardController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TextArea; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.Clipboard; import javafx.stage.Window; import mara.mybox.db.data.TextClipboard; import mara.mybox.db.table.TableTextClipboard; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.TextClipboardTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.cell.TableDateCell; import mara.mybox.fxml.cell.TableNumberCell; import mara.mybox.fxml.cell.TableTextTruncCell; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2021-7-3 * @License Apache License Version 2.0 */ public class TextInMyBoxClipboardController extends BaseSysTableController<TextClipboard> { protected Clipboard clipboard; @FXML protected TableColumn<TextClipboard, String> textColumn; @FXML protected TableColumn<TextClipboard, Date> timeColumn; @FXML protected TableColumn<TextClipboard, Long> lengthColumn; @FXML protected TextArea textArea; @FXML protected Label textLabel; @FXML protected CheckBox noDupCheck, wrapCheck; public TextInMyBoxClipboardController() { baseTitle = Languages.message("TextInMyBoxClipboard"); TipsLabelKey = "TextInMyBoxClipboardTips"; } @Override public void setTableDefinition() { tableDefinition = new TableTextClipboard(); } @Override protected void initColumns() { try { super.initColumns(); textColumn.setCellValueFactory(new PropertyValueFactory<>("text")); textColumn.setCellFactory(new TableTextTruncCell()); lengthColumn.setCellValueFactory(new PropertyValueFactory<>("length")); lengthColumn.setCellFactory(new TableNumberCell(true)); timeColumn.setCellValueFactory(new PropertyValueFactory<>("createTime")); timeColumn.setCellFactory(new TableDateCell()); } catch (Exception e) { MyBoxLog.error(e); } } @Override protected void checkSelected() { if (isSettingValues) { return; } super.checkSelected(); TextClipboard selected = selectedItem(); if (selected != null) { textArea.setText(selected.getText()); } } @Override public void initControls() { try { super.initControls(); clipboard = Clipboard.getSystemClipboard(); copyToSystemClipboardButton.setDisable(true); copyToMyBoxClipboardButton.setDisable(true); editButton.setDisable(true); noDupCheck.setSelected(UserConfig.getBoolean("TextClipboardNoDuplication", true)); noDupCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean ov, Boolean nv) { UserConfig.setBoolean("TextClipboardNoDuplication", noDupCheck.isSelected()); } }); wrapCheck.setSelected(UserConfig.getBoolean(baseName + "Wrap", true)); wrapCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "Wrap", newValue); textArea.setWrapText(newValue); } }); textArea.setWrapText(wrapCheck.isSelected()); textArea.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String ov, String nv) { textChanged(nv); } }); refreshAction(); } catch (Exception e) { MyBoxLog.debug(e); } } public void textChanged(String nv) { int len = nv == null ? 0 : nv.length(); textLabel.setText(Languages.message("CharactersNumber") + ": " + len); copyToSystemClipboardButton.setDisable(len == 0); copyToMyBoxClipboardButton.setDisable(len == 0); editButton.setDisable(len == 0); } @FXML @Override public void pasteContentInSystemClipboard() { String clip = clipboard.getString(); if (clip == null) { popInformation(Languages.message("NoTextInClipboard")); return; } TextClipboardTools.copyToMyBoxClipboard(myController, clip); } @FXML @Override public void copyToMyBoxClipboard() { String s = textArea.getSelectedText(); if (s == null || s.isEmpty()) { s = textArea.getText(); } if (s == null || s.isEmpty()) { popError(Languages.message("SelectToHandle")); return; } TextClipboardTools.copyToMyBoxClipboard(myController, s); } @FXML @Override public void copyToSystemClipboard() { String s = textArea.getSelectedText(); if (s == null || s.isEmpty()) { s = textArea.getText(); } if (s == null || s.isEmpty()) { popError(Languages.message("SelectToHandle")); return; } TextClipboardTools.copyToSystemClipboard(myController, s); } @FXML @Override public void editAction() { String s = textArea.getSelectedText(); if (s == null || s.isEmpty()) { s = textArea.getText(); } if (s == null || s.isEmpty()) { popError(Languages.message("NoData")); return; } TextEditorController.edit(s); } @FXML @Override public void refreshAction() { loadTableData(); updateStatus(); } @Override public void updateStatus() { super.updateStatus(); if (TextClipboardTools.isMonitoring()) { bottomLabel.setText(Languages.message("MonitoringTextInSystemClipboard")); } else { bottomLabel.setText(Languages.message("NotMonitoringTextInSystemClipboard")); } } /* static methods */ public static TextInMyBoxClipboardController oneOpen() { TextInMyBoxClipboardController controller = null; List<Window> windows = new ArrayList<>(); windows.addAll(Window.getWindows()); for (Window window : windows) { Object object = window.getUserData(); if (object == null) { continue; } if (object instanceof TextInMyBoxClipboardController) { controller = (TextInMyBoxClipboardController) object; controller.refreshAction(); break; } } if (controller == null) { controller = (TextInMyBoxClipboardController) WindowTools.openStage(Fxmls.TextInMyBoxClipboardFxml); } controller.requestMouse(); return controller; } public static void updateMyBoxClipboard() { Platform.runLater(() -> { List<Window> windows = new ArrayList<>(); windows.addAll(Window.getWindows()); for (Window window : windows) { Object object = window.getUserData(); if (object == null) { continue; } if (object instanceof TextClipboardPopController) { ((TextClipboardPopController) object).refreshAction(); } if (object instanceof TextInMyBoxClipboardController) { ((TextInMyBoxClipboardController) object).refreshAction(); } } }); Platform.requestNextPulse(); } public static void updateMyBoxClipboardStatus() { Platform.runLater(() -> { List<Window> windows = new ArrayList<>(); windows.addAll(Window.getWindows()); for (Window window : windows) { Object object = window.getUserData(); if (object == null) { continue; } if (object instanceof TextClipboardPopController) { ((TextClipboardPopController) object).updateStatus(); } if (object instanceof TextInMyBoxClipboardController) { ((TextInMyBoxClipboardController) object).updateStatus(); } } }); Platform.requestNextPulse(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/FindReplaceBatchOptions.java
released/MyBox/src/main/java/mara/mybox/controller/FindReplaceBatchOptions.java
package mara.mybox.controller; import java.nio.charset.Charset; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.TextTools; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2020-11-16 * @License Apache License Version 2.0 */ public class FindReplaceBatchOptions extends ControlFindReplace { protected Charset charset; protected boolean autoDetermine; @FXML protected ToggleGroup charsetGroup; @FXML protected ComboBox<String> encodeBox; public FindReplaceBatchOptions() { TipsLabelKey = "TextReplaceBatchTips"; } @Override public void setControls() { try { super.setControls(); if (charsetGroup != null) { charsetGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkCharset(); } }); } if (encodeBox != null) { List<String> setNames = TextTools.getCharsetNames(); encodeBox.getItems().addAll(setNames); encodeBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { checkCharset(); } }); encodeBox.getSelectionModel().select(Charset.defaultCharset().name()); } } catch (Exception e) { MyBoxLog.error(e); } } protected void checkCharset() { RadioButton selected = (RadioButton) charsetGroup.getSelectedToggle(); if (Languages.message("DetermineAutomatically").equals(selected.getText())) { autoDetermine = true; encodeBox.setDisable(true); } else { autoDetermine = false; charset = Charset.forName(encodeBox.getSelectionModel().getSelectedItem()); encodeBox.setDisable(false); } } @Override protected void checkFindInput(String string) { } @Override protected boolean checkReplaceInput(String string) { return true; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BaseBatchFileController.java
released/MyBox/src/main/java/mara/mybox/controller/BaseBatchFileController.java
package mara.mybox.controller; import java.io.File; import mara.mybox.data.FileInformation; /** * @Author Mara * @CreateDate 2019-4-28 * @License Apache License Version 2.0 */ public class BaseBatchFileController extends BaseBatchController<FileInformation> { public void startFile(File file) { isSettingValues = true; tableData.clear(); tableData.add(new FileInformation(file)); tableView.refresh(); isSettingValues = false; startAction(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImagesPlayController.java
released/MyBox/src/main/java/mara/mybox/controller/ImagesPlayController.java
package mara.mybox.controller; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.TextInputDialog; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.image.data.ImageFileInformation; import mara.mybox.image.data.ImageInformation; import mara.mybox.image.file.ImageFileReaders; import mara.mybox.tools.FileNameTools; import mara.mybox.value.AppValues; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; import org.apache.pdfbox.Loader; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.poi.sl.usermodel.Slide; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.sl.usermodel.SlideShowFactory; /** * @Author Mara * @CreateDate 2021-5-29 * @License Apache License Version 2.0 */ public class ImagesPlayController extends BaseFileController { protected List<ImageInformation> imageInfos; protected int loadWidth, framesNumber, frameIndex, queueSize, fromFrame, toFrame; protected String fileFormat, pdfPassword, inPassword; protected LoadingController loading; protected long memoryThreadhold; protected Thread loadThread; protected PDDocument pdfDoc; protected ImageType pdfImageType; protected PDFRenderer pdfRenderer; protected SlideShow ppt; protected ImageInputStream imageInputStream; protected ImageReader imageReader; protected Thread frameThread; protected FxSingletonTask frameTask; @FXML protected ToggleGroup typeGroup; @FXML protected RadioButton imagesRadio, pdfRadio, pptRadio; @FXML protected ComboBox<String> loadWidthSelector; @FXML protected CheckBox transparentBackgroundCheck; @FXML protected Button goFramesButton; @FXML protected VBox fileVBox, pdfBox, viewBox, playBox; @FXML protected TextField fromInput, toInput; @FXML protected FlowPane framesPane; @FXML protected ControlPlay playController; @FXML protected ControlImageView viewController; public ImagesPlayController() { baseTitle = message("ImagesPlay"); TipsLabelKey = "ImagesPlayTips"; } @Override public void initControls() { try { super.initControls(); memoryThreadhold = 200 * 1024 * 1024; imageInfos = new ArrayList<>(); typeGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue ov, Toggle oldValue, Toggle newValue) { if (pdfRadio.isSelected()) { setFileType(VisitHistory.FileType.PDF); if (!fileVBox.getChildren().contains(pdfBox)) { fileVBox.getChildren().add(3, pdfBox); NodeStyleTools.refreshStyle(pdfBox); } } else if (pptRadio.isSelected()) { setFileType(VisitHistory.FileType.PPTS); if (fileVBox.getChildren().contains(pdfBox)) { fileVBox.getChildren().remove(pdfBox); } } else { setFileType(VisitHistory.FileType.Image); if (fileVBox.getChildren().contains(pdfBox)) { fileVBox.getChildren().remove(pdfBox); } } } }); // Displayed values are 1-based while internal values are 0-based fromFrame = 0; toFrame = -1; fromInput.setText("1"); toInput.setText("-1"); List<String> values = Arrays.asList(message("OriginalSize"), "512", "1024", "256", "128", "2048", "100", "80", "4096"); loadWidthSelector.getItems().addAll(values); loadWidth = UserConfig.getInt(baseName + "LoadWidth", -1); if (loadWidth <= 0) { loadWidth = -1; loadWidthSelector.getSelectionModel().select(0); } else { loadWidthSelector.setValue(loadWidth + ""); } loadWidthSelector.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue ov, String oldValue, String newValue) { if (message("OriginalSize").equals(newValue)) { loadWidth = -1; } else { try { loadWidth = Integer.parseInt(newValue); if (loadWidth <= 0) { loadWidth = -1; } ValidationTools.setEditorNormal(loadWidthSelector); } catch (Exception e) { ValidationTools.setEditorBadStyle(loadWidthSelector); } } } }); transparentBackgroundCheck.setSelected(UserConfig.getBoolean(baseName + "Transparent", false)); transparentBackgroundCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { UserConfig.setBoolean(baseName + "Transparent", transparentBackgroundCheck.isSelected()); if (fileFormat != null && fileFormat.equalsIgnoreCase("pdf")) { reloadImages(); } } }); fileVBox.getChildren().remove(pdfBox); frameThread = new Thread() { @Override public void run() { displayFrame(playController.currentIndex); } }; playController.setParameters(this, frameThread, null); playController.stopped.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { closeFile(); } }); viewBox.disableProperty().bind(viewController.imageView.imageProperty().isNull()); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(toInput, new Tooltip(message("ToPageComments"))); } catch (Exception e) { MyBoxLog.debug(e); } } public void setAsPDF() { pdfRadio.setSelected(true); } public void setAsPPT() { pptRadio.setSelected(true); } @Override public void dpiChanged() { if (fileFormat != null && fileFormat.equalsIgnoreCase("pdf")) { reloadImages(); } } public boolean checkMemory() { Runtime r = Runtime.getRuntime(); long availableMem = r.maxMemory() - (r.totalMemory() - r.freeMemory()); return availableMem >= memoryThreadhold; } public void clearList() { if (timer != null) { timer.cancel(); } if (task != null) { task.cancel(); } framesNumber = 0; frameIndex = 0; sourceFile = null; fileFormat = null; pdfPassword = null; imageInfos.clear(); playController.clear(); viewController.loadImage(null); } @Override public void sourceFileChanged(File file) { clearList(); if (file == null) { return; } String format = FileNameTools.ext(file.getName()); if (format == null || format.isBlank()) { popError(message("NotSupport")); return; } sourceFile = file; fileFormat = format; task = new FxSingletonTask<Void>(this) { @Override protected boolean handle() { if (fileFormat.equalsIgnoreCase("pdf")) { return loadPDF(); } else if (fileFormat.equalsIgnoreCase("ppt") || fileFormat.equalsIgnoreCase("pptx")) { return loadPPT(); } else if (fileFormat.equalsIgnoreCase("ico") || fileFormat.equalsIgnoreCase("icon")) { return loadIconFile(this); } else { return loadImageFile(this); } } @Override protected void whenSucceeded() { if (error != null && !error.isBlank()) { alertError(error); } playImages(); } }; loading = start(task); } protected boolean loadImageFile(FxTask currentTask) { imageReader = null; imageInfos.clear(); Platform.runLater(() -> { imagesRadio.setSelected(true); }); try { openImageFile(); if (imageReader == null) { return false; } ImageFileInformation fileInfo = new ImageFileInformation(sourceFile); if (loading != null) { loading.setInfo(message("Loading") + " " + message("MetaData")); } ImageFileReaders.readImageFileMetaData(currentTask, imageReader, fileInfo); if (currentTask == null || !currentTask.isWorking()) { loading.setInfo(message("Canceled")); return false; } imageInfos.addAll(fileInfo.getImagesInformation()); if (imageInfos == null) { imageReader.dispose(); return false; } framesNumber = imageInfos.size(); if (!fileFormat.equalsIgnoreCase("gif")) { for (int i = 0; i < framesNumber; i++) { imageInfos.get(i).setDuration(playController.timeValue); } } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } MyBoxLog.error(e); return false; } return task != null && !task.isCancelled(); } protected void openImageFile() { try { closeFile(); if (sourceFile == null) { return; } imageInputStream = ImageIO.createImageInputStream(sourceFile); imageReader = ImageFileReaders.getReader(imageInputStream, FileNameTools.ext(sourceFile.getName())); if (imageReader != null) { imageReader.setInput(imageInputStream, false, false); } } catch (Exception e) { if (task != null) { task.setError(e.toString()); } MyBoxLog.error(e); } } protected boolean loadIconFile(FxTask currentTask) { imageInfos.clear(); Platform.runLater(() -> { imagesRadio.setSelected(true); }); if (sourceFile == null) { return false; } try { ImageFileInformation finfo = ImageFileInformation.readIconFile(currentTask, sourceFile); if (currentTask == null || !currentTask.isWorking()) { return false; } imageInfos.addAll(finfo.getImagesInformation()); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } MyBoxLog.error(e); return false; } return true; } public boolean loadPPT() { imageInfos.clear(); Platform.runLater(() -> { pptRadio.setSelected(true); }); try { openPPT(); if (ppt == null) { return false; } List<Slide> slides = ppt.getSlides(); int width = ppt.getPageSize().width; int height = ppt.getPageSize().height; framesNumber = slides.size(); for (int i = 0; i < framesNumber; i++) { ImageInformation imageInfo = new ImageInformation(sourceFile); imageInfo.setIndex(i); imageInfo.setWidth(width); imageInfo.setHeight(height); imageInfo.setDuration(playController.timeValue); imageInfos.add(imageInfo); } } catch (Exception e) { MyBoxLog.error(e); return false; } return true; } protected void openPPT() { try { closeFile(); if (sourceFile == null) { return; } ppt = SlideShowFactory.create(sourceFile); } catch (Exception e) { if (task != null) { task.setError(e.toString()); } MyBoxLog.error(e); } } public boolean loadPDF() { imageInfos.clear(); Platform.runLater(() -> { pdfRadio.setSelected(true); }); try { openPDF(inPassword); inPassword = null; if (pdfDoc == null) { return false; } pdfImageType = ImageType.RGB; if (transparentBackgroundCheck.isSelected()) { pdfImageType = ImageType.ARGB; } framesNumber = pdfDoc.getNumberOfPages(); for (int i = 0; i < framesNumber; i++) { ImageInformation imageInfo = new ImageInformation(sourceFile); imageInfo.setIndex(i); imageInfo.setDuration(playController.timeValue); imageInfo.setDpi(dpi); imageInfo.setPassword(pdfPassword); imageInfos.add(imageInfo); } } catch (Exception e) { MyBoxLog.error(e); return false; } return true; } protected void openPDF(String password) { closeFile(); if (sourceFile == null) { return; } try { pdfDoc = Loader.loadPDF(sourceFile, password); pdfPassword = password; } catch (InvalidPasswordException e) { try { Platform.runLater(() -> { TextInputDialog dialog = new TextInputDialog(); dialog.setContentText(message("UserPassword")); Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow(); stage.setAlwaysOnTop(true); stage.toFront(); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { pdfPassword = result.get(); } synchronized (sourceFile) { sourceFile.notifyAll(); } }); synchronized (sourceFile) { sourceFile.wait(); } Platform.requestNextPulse(); try { pdfDoc = Loader.loadPDF(sourceFile, pdfPassword); } catch (Exception ee) { error = ee.toString(); sourceFile = null; } } catch (Exception eee) { error = eee.toString(); } } catch (Exception eeee) { error = eeee.toString(); } if (pdfDoc != null) { pdfRenderer = new PDFRenderer(pdfDoc); } } public void loadImages(List<ImageInformation> infos) { try { clearList(); if (infos == null || infos.isEmpty()) { return; } for (ImageInformation info : infos) { ImageInformation ninfo = info.cloneAttributes(); if (ninfo.getDuration() < 0) { ninfo.setDuration(playController.timeValue); } imageInfos.add(ninfo); if (ninfo.getRegion() != null) { } } framesNumber = imageInfos.size(); playImages(); } catch (Exception e) { MyBoxLog.error(e); } } public synchronized boolean playImages() { try { if (imageInfos == null || framesNumber < 1) { return false; } int start = fromFrame, end = toFrame; if (start < 0 || start >= framesNumber) { start = 0; } if (end < 0 || end >= framesNumber) { end = framesNumber - 1; } if (start > end) { return false; } viewController.reset(); playController.play(framesNumber, start, end); return true; } catch (Exception e) { MyBoxLog.error(e); return false; } } @FXML public void goFrames() { if (fileFormat == null) { return; } String value = fromInput.getText(); int f = AppValues.InvalidInteger; if (value == null || value.isBlank()) { f = 0; fromInput.setStyle(null); } else { try { int v = Integer.parseInt(value); if (v < 0) { fromInput.setStyle(UserConfig.badStyle()); } else { f = v - 1; fromInput.setStyle(null); } } catch (Exception e) { fromInput.setStyle(UserConfig.badStyle()); } } int t = AppValues.InvalidInteger; value = toInput.getText(); if (value == null || value.isBlank()) { t = -1; toInput.setStyle(null); } else { try { int v = Integer.parseInt(value); if (v < 0) { t = -1; toInput.setStyle(null); } else { t = v - 1; toInput.setStyle(null); } } catch (Exception e) { toInput.setStyle(UserConfig.badStyle()); } } if (f == AppValues.InvalidInteger || t == AppValues.InvalidInteger || (t >= 0 && f > t)) { popError(message("InvalidParametes")); return; } fromFrame = f; toFrame = t; reloadImages(); } public void reloadImages() { if (sourceFile != null) { sourceFileChanged(sourceFile); } else if (imageInfos != null && !imageInfos.isEmpty()) { List<ImageInformation> infos = new ArrayList<>(); infos.addAll(imageInfos); loadImages(infos); } } @FXML public void viewFile() { try { if (fileFormat == null) { ImageEditorController.openFile(sourceFile); } else if (fileFormat.equalsIgnoreCase("pdf")) { PdfViewController controller = (PdfViewController) openStage(Fxmls.PdfViewFxml); controller.loadFile(sourceFile, null, frameIndex); } else if (fileFormat.equalsIgnoreCase("ppt") || fileFormat.equalsIgnoreCase("pptx")) { PptViewController controller = (PptViewController) openStage(Fxmls.PptViewFxml); controller.loadFile(sourceFile, frameIndex); } else { ImageEditorController.openFile(sourceFile); } } catch (Exception e) { MyBoxLog.error(e); } } @FXML public void editFrames() { ImagesEditorController.openImages(imageInfos); } public void displayFrame(int index) { if (frameTask != null) { frameTask.cancel(); } if (imageInfos == null) { playController.clear(); viewController.loadImage(null); return; } frameTask = new FxSingletonTask<Void>(this) { ImageInformation info; Image image; @Override protected boolean handle() { try { info = imageInfos.get(index); frameIndex = index; image = thumb(this, info); return true; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { if (image == null) { return; } viewController.loadImage(myController, image, framesNumber, frameIndex); playController.refreshList(); info.setThumbnail(null); // release memory } @Override protected void whenFailed() { } }; start(frameTask, false); } protected Image thumb(FxTask thumbTask, ImageInformation info) { try { if (info == null) { return null; } double imageWidth = info.getWidth(); double targetWidth = loadWidth <= 0 ? imageWidth : loadWidth; if (info.getRegion() == null) { Image thumb = info.getThumbnail(); if (thumb != null && (int) thumb.getWidth() == (int) targetWidth) { return thumb; } } info.setThumbnail(null); if (fileFormat == null) { info.loadThumbnail(thumbTask, loadWidth); } else if (fileFormat.equalsIgnoreCase("pdf")) { if (pdfRenderer == null) { openPDF(pdfPassword); } if (pdfRenderer == null) { return null; } ImageInformation.readPDF(thumbTask, pdfRenderer, pdfImageType, info, loadWidth); } else if (fileFormat.equalsIgnoreCase("ppt") || fileFormat.equalsIgnoreCase("pptx")) { if (ppt == null) { openPPT(); } ImageInformation.readPPT(thumbTask, ppt, info, loadWidth); } else if (sourceFile != null) { if (imageReader == null) { openImageFile(); } ImageInformation.readImage(thumbTask, imageReader, info, loadWidth); } else { info.loadThumbnail(thumbTask, loadWidth); } return info.getThumbnail(); } catch (Exception e) { MyBoxLog.error(e); return null; } } public void closeFile() { try { if (imageInputStream != null) { imageInputStream.close(); imageInputStream = null; } imageReader = null; if (pdfDoc != null) { pdfDoc.close(); pdfDoc = null; } pdfRenderer = null; if (ppt != null) { ppt.close(); ppt = null; } } catch (Exception e) { playController.clear(); MyBoxLog.debug(e); } } @Override public boolean handleKeyEvent(KeyEvent event) { if (viewBox.isFocused() || viewBox.isFocusWithin()) { if (viewController.handleKeyEvent(event)) { return true; } } else if (playBox.isFocused() || playBox.isFocusWithin()) { if (playController.handleKeyEvent(event)) { return true; } } if (super.handleKeyEvent(event)) { return true; } if (viewController.handleKeyEvent(event)) { return true; } return playController.handleKeyEvent(event); } @Override public void cleanPane() { try { playController.clear(); if (loading != null) { loading.cancelAction(); loading = null; } closeFile(); } catch (Exception e) { } super.cleanPane(); } /* static */ public static ImagesPlayController open() { try { ImagesPlayController controller = (ImagesPlayController) WindowTools.openStage(Fxmls.ImagesPlayFxml); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static ImagesPlayController playImages(List<ImageInformation> infos) { try { ImagesPlayController controller = open(); controller.loadImages(infos); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static ImagesPlayController playPDF(File file, String password) { try { ImagesPlayController controller = open(); if (controller != null) { controller.requestMouse(); controller.inPassword = password; controller.sourceFileChanged(file); } return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static ImagesPlayController playFile(File file) { try { ImagesPlayController controller = open(); if (controller != null) { controller.requestMouse(); controller.sourceFileChanged(file); } return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/HtmlMergeAsPDFController.java
released/MyBox/src/main/java/mara/mybox/controller/HtmlMergeAsPDFController.java
package mara.mybox.controller; import java.io.File; import java.util.ArrayList; import java.util.List; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import mara.mybox.data.FileInformation; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.tools.FileDeleteTools; import mara.mybox.tools.HtmlReadTools; import mara.mybox.tools.TextFileTools; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-10-21 * @License Apache License Version 2.0 */ public class HtmlMergeAsPDFController extends BaseBatchFileController { protected StringBuilder mergedHtml; @FXML protected ControlHtml2PdfOptions optionsController; @FXML protected CheckBox deleteCheck; public HtmlMergeAsPDFController() { baseTitle = message("HtmlMergeAsPDF"); targetFileSuffix = "pdf"; } @Override public void setFileType() { setFileType(VisitHistory.FileType.Html, VisitHistory.FileType.PDF); } @Override public void initControls() { try { super.initControls(); optionsController.setControls(baseName, true); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean makeMoreParameters() { try { targetFile = makeTargetFile(); if (targetFile == null) { return false; } lastTargetName = targetFile.getAbsolutePath(); targetPath = targetFile.getParentFile(); mergedHtml = new StringBuilder(); String head = "<html>\n" + " <head>\n" + " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" + " </head>\n" + " <body>\n"; mergedHtml.append(head); return super.makeMoreParameters(); } catch (Exception e) { MyBoxLog.debug(e); return false; } } @Override public String handleFile(FxTask currentTask, File srcFile, File targetPath) { try { String html = TextFileTools.readTexts(currentTask, srcFile); if (currentTask == null || !currentTask.isWorking()) { return message("Canceled"); } if (html == null) { return message("Failed"); } String body = HtmlReadTools.body(html, false); mergedHtml.append(body); return message("Successful"); } catch (Exception e) { MyBoxLog.error(e); return message("Failed"); } } @Override public void afterHandleFiles(FxTask currentTask) { try { mergedHtml.append(" </body>\n</html>\n"); String result = optionsController.html2pdf(currentTask, mergedHtml.toString(), targetFile); if (currentTask == null || !currentTask.isWorking()) { updateLogs(message("Canceled"), true, true); return; } if (!message("Successful").equals(result)) { updateLogs(result, true, true); return; } targetFileGenerated(targetFile); if (deleteCheck.isSelected()) { List<FileInformation> sources = new ArrayList<>(); sources.addAll(tableData); for (int i = sources.size() - 1; i >= 0; --i) { if (currentTask == null || !currentTask.isWorking()) { updateLogs(message("Canceled"), true, true); return; } try { FileInformation source = sources.get(i); FileDeleteTools.delete(source.getFile()); tableData.remove(i); } catch (Exception e) { } } } } catch (Exception e) { updateLogs(e.toString(), true, true); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/AlarmClockRunController.java
released/MyBox/src/main/java/mara/mybox/controller/AlarmClockRunController.java
package mara.mybox.controller; import java.io.File; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.media.AudioClip; import mara.mybox.db.data.AlarmClock; import mara.mybox.fxml.FxFileTools; import mara.mybox.fxml.SoundTools; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2018-7-15 * @Version 1.0 * @License Apache License Version 2.0 */ public class AlarmClockRunController extends BaseController { private AlarmClock alarm; private AudioClip player; private Task playTask; @FXML protected Label descLabel, soundLabel, timeLabel; public AlarmClockRunController() { baseTitle = Languages.message("AlarmClock"); } @FXML public void manageAction(ActionEvent event) { knowAction(event); AlarmClockController.oneOpen(); } public void inactive(ActionEvent event) { // alarm.setIsActive(false); // alarm.setStatus(Languages.message("Inactive")); // alarm.setNextTime(-1); // alarm.setNext(""); // AlarmClock.scheduleAlarmClock(alarm); // AlarmClock.writeAlarmClock(alarm); // knowAction(event); // AlarmClockController controller = AlarmClockController.oneOpen(); // if (controller != null) { // controller.alertClockTableController.refreshAction(); // } } @FXML public void knowAction(ActionEvent event) { if (player != null) { player.stop(); player = null; } closeStage(); } public void runAlarm(final AlarmClock alarm) { this.alarm = alarm; getMyStage().setTitle(baseTitle + " - " + alarm.getDescription()); descLabel.setText(alarm.getDescription()); String soundString = alarm.getSound() + " "; if (alarm.isIsSoundLoop()) { if (alarm.isIsSoundContinully()) { soundString += Languages.message("Continually"); } else { soundString += Languages.message("LoopTimes") + " " + alarm.getSoundLoopTimes(); } } // soundLabel.setText(soundString); // String typeString = getTypeString(alarm); // if (alarm.getNext() != null) { // typeString += " " + Languages.message("NextTime") + " " + alarm.getNext(); // } // timeLabel.setText(typeString); playTask = new Task<Void>() { @Override protected Void call() { try { String sound = alarm.getSound(); if (Languages.message("Meow").equals(sound)) { File miao = FxFileTools.getInternalFile("/sound/miao4.mp3", "sound", "miao4.mp3"); sound = miao.getAbsolutePath(); } player = SoundTools.clip(new File(sound), alarm.getVolume()); // if (alarm.isIsSoundLoop()) { // if (alarm.isIsSoundContinully()) { // player.loop(Clip.LOOP_CONTINUOUSLY); // } else { // player.loop(alarm.getSoundLoopTimes() - 1); // } // } // player.start(); } catch (Exception e) { } return null; } }; start(playTask, false, null); } public AlarmClock getAlarm() { return alarm; } public void setAlarm(AlarmClock alarm) { this.alarm = alarm; } public Label getDescLabel() { return descLabel; } public void setDescLabel(Label descLabel) { this.descLabel = descLabel; } public Label getSoundLabel() { return soundLabel; } public void setSoundLabel(Label soundLabel) { this.soundLabel = soundLabel; } public Label getTimeLabel() { return timeLabel; } public void setTimeLabel(Label timeLabel) { this.timeLabel = timeLabel; } @Override public void cleanPane() { try { if (playTask != null && !playTask.isDone()) { playTask.cancel(); playTask = null; } } catch (Exception e) { } super.cleanPane(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImageEdgeController.java
released/MyBox/src/main/java/mara/mybox/controller/ImageEdgeController.java
package mara.mybox.controller; import java.util.List; import javafx.embed.swing.SwingFXUtils; import javafx.fxml.FXML; import javafx.scene.image.Image; import mara.mybox.db.data.ConvolutionKernel; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxTask; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.image.PixelDemos; import mara.mybox.image.data.ImageConvolution; import mara.mybox.image.data.ImageScope; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2019-9-2 * @License Apache License Version 2.0 */ public class ImageEdgeController extends BasePixelsController { protected ConvolutionKernel kernel; @FXML protected ControlImageEdge edgeController; public ImageEdgeController() { baseTitle = message("EdgeDetection"); } @Override protected void initMore() { try { super.initMore(); operation = message("EdgeDetection"); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean checkOptions() { if (!super.checkOptions()) { return false; } kernel = edgeController.pickValues(); return kernel != null; } @Override protected Image handleImage(FxTask currentTask, Image inImage, ImageScope inScope) { try { ImageConvolution convolution = ImageConvolution.create(); convolution.setImage(inImage) .setScope(inScope) .setKernel(kernel) .setExcludeScope(excludeScope()) .setSkipTransparent(skipTransparent()) .setTask(currentTask); operation = kernel.getName(); opInfo = message("Color") + ": " + kernel.getColor(); return convolution.startFx(); } catch (Exception e) { displayError(e.toString()); return null; } } @Override protected void makeDemoFiles(FxTask currentTask, List<String> files, Image demoImage) { PixelDemos.edge(currentTask, files, SwingFXUtils.fromFXImage(demoImage, null), srcFile()); } /* static methods */ public static ImageEdgeController open(BaseImageController parent) { try { if (parent == null) { return null; } ImageEdgeController controller = (ImageEdgeController) WindowTools.referredStage( parent, Fxmls.ImageEdgeFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ChromaticAdaptationMatrixController.java
released/MyBox/src/main/java/mara/mybox/controller/ChromaticAdaptationMatrixController.java
package mara.mybox.controller; import java.util.Map; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import mara.mybox.color.ChromaticAdaptation; import mara.mybox.data.StringTable; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.tools.DoubleMatrixTools; import mara.mybox.tools.HtmlWriteTools; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-07-24 * @License Apache License Version 2.0 */ // http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html public class ChromaticAdaptationMatrixController extends ChromaticityBaseController { @FXML public WhitePointController sourceWPController, targetWPController; @FXML protected Button calculateButton, calculateAllButton, exportButton; @FXML protected TextField scaleMatricesInput; @FXML protected TextArea allArea; @FXML protected HtmlTableController matrixController; public ChromaticAdaptationMatrixController() { baseTitle = Languages.message("ChromaticAdaptationMatrix"); exportName = "ChromaticAdaptationMatrices"; } @Override public void initControls() { try { super.initControls(); initCalculation(); initAll(); } catch (Exception e) { MyBoxLog.error(e); } } public void initCalculation() { try { initOptions(); calculateButton.disableProperty().bind(Bindings.isEmpty(scaleInput.textProperty()) .or(scaleInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(sourceWPController.xInput.textProperty())) .or(sourceWPController.xInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(sourceWPController.yInput.textProperty())) .or(sourceWPController.yInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(sourceWPController.zInput.textProperty())) .or(sourceWPController.zInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(targetWPController.xInput.textProperty())) .or(targetWPController.xInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(targetWPController.yInput.textProperty())) .or(targetWPController.yInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(targetWPController.zInput.textProperty())) .or(targetWPController.zInput.styleProperty().isEqualTo(UserConfig.badStyle())) ); } catch (Exception e) { } } public void initAll() { try { scaleMatricesInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { int p = Integer.parseInt(scaleMatricesInput.getText()); if (p <= 0) { scaleMatricesInput.setStyle(UserConfig.badStyle()); } else { scale = p; scaleMatricesInput.setStyle(null); UserConfig.setInt("MatrixDecimalScale", scale); } } catch (Exception e) { scaleMatricesInput.setStyle(UserConfig.badStyle()); } } }); int p = UserConfig.getInt("MatrixDecimalScale", 8); scaleMatricesInput.setText(p + ""); calculateAllButton.disableProperty().bind(scaleMatricesInput.textProperty().isEmpty() .or(scaleMatricesInput.styleProperty().isEqualTo(UserConfig.badStyle())) ); exportButton.disableProperty().bind(allArea.textProperty().isEmpty() ); } catch (Exception e) { } } @FXML public void calculateAction(ActionEvent event) { webView.getEngine().loadContent(""); if (calculateButton.isDisabled()) { return; } double[] swp = sourceWPController.relative; double[] twp = targetWPController.relative; if (swp == null || twp == null) { return; } Map<String, Object> run = ChromaticAdaptation.matrixDemo( swp[0], swp[1], swp[2], twp[0], twp[1], twp[2], algorithm, scale); String s = DoubleMatrixTools.print((double[][]) run.get("matrix"), 0, scale) + "\n\n----------------" + Languages.message("CalculationProcedure") + "----------------\n" + Languages.message("ReferTo") + ": \n" + " http://www.thefullwiki.org/Standard_illuminant#cite_note-30 \n" + " http://brucelindbloom.com/index.html?Eqn_ChromAdapt.html \n\n" + (String) run.get("procedure"); webView.getEngine().loadContent(HtmlWriteTools.codeToHtml(s)); } @FXML public void calculateAllAction(ActionEvent event) { if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { private StringTable table; private String allTexts; @Override protected boolean handle() { table = ChromaticAdaptation.table(scale); allTexts = ChromaticAdaptation.allTexts(scale); return true; } @Override protected void whenSucceeded() { matrixController.loadTable(table); allArea.setText(allTexts); allArea.home(); } }; start(task); } @Override public String exportTexts() { return allArea.getText(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImageSplitController.java
released/MyBox/src/main/java/mara/mybox/controller/ImageSplitController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioButton; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.text.Text; import mara.mybox.data.DoublePoint; import mara.mybox.data.DoubleShape; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.PopTools; import static mara.mybox.fxml.style.NodeStyleTools.attributeTextStyle; import mara.mybox.fxml.style.StyleTools; import mara.mybox.image.data.ImageInformation; import mara.mybox.tools.IntTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-8-8 * @License Apache License Version 2.0 */ public class ImageSplitController extends BaseShapeController { protected List<ImageInformation> imageInfos; protected List<Integer> rows, cols; protected int rowsNumber, colsNumber, width, height; protected SimpleBooleanProperty splitValid; protected SplitMethod splitMethod; public static enum SplitMethod { Predefined, ByNumber, BySize, Customize } @FXML protected ToggleGroup splitGroup; @FXML protected RadioButton predefinedRadio, sizeRadio, numbersRadio, customizeRadio; @FXML protected FlowPane splitPredefinedPane, splitSizePane, splitNumberPane, splitCustomized1Pane, splitCustomized2Pane; @FXML protected TextField rowsInput, colsInput, customizedRowsInput, customizedColsInput, widthInput, heightInput; @FXML protected CheckBox displaySizeCheck; @FXML protected VBox splitOptionsBox, splitCustomizeBox; @FXML protected Label promptLabel, sizeLabel; public ImageSplitController() { baseTitle = message("ImageSplit"); TipsLabelKey = "ImageSplitTips"; } @Override public void initValues() { try { super.initValues(); imageInfos = new ArrayList<>(); splitValid = new SimpleBooleanProperty(false); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void initControls() { try { super.initControls(); displaySizeCheck.setSelected(UserConfig.getBoolean(baseName + "DisplaySize", true)); displaySizeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { UserConfig.setBoolean(baseName + "DisplaySize", displaySizeCheck.isSelected()); indicateSplit(); } }); splitGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkSplitMethod(); } }); checkSplitMethod(); rightPane.disableProperty().bind(imageView.imageProperty().isNull()); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean afterImageLoaded() { try { imageInfos.clear(); if (!super.afterImageLoaded()) { return false; } cols = new ArrayList<>(); rows = new ArrayList<>(); splitValid.set(false); clearCols(); clearRows(); return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } protected void checkSplitMethod() { try { initSplit(); splitOptionsBox.getChildren().clear(); if (predefinedRadio.isSelected()) { splitMethod = SplitMethod.Predefined; splitOptionsBox.getChildren().addAll(splitPredefinedPane); promptLabel.setText(""); } else if (customizeRadio.isSelected()) { splitMethod = SplitMethod.Customize; splitOptionsBox.getChildren().addAll(splitCustomizeBox, goButton, promptLabel); promptLabel.setText(message("SplitImageCustom")); } else if (numbersRadio.isSelected()) { splitMethod = SplitMethod.ByNumber; splitOptionsBox.getChildren().addAll(splitNumberPane, goButton); promptLabel.setText(""); rowsInput.setText("3"); colsInput.setText("3"); } else if (sizeRadio.isSelected()) { splitMethod = SplitMethod.BySize; splitOptionsBox.getChildren().addAll(splitSizePane, goButton, promptLabel); promptLabel.setText(message("SplitImageSize")); widthInput.setText((int) (imageWidth() / (widthRatio() * 3)) + ""); heightInput.setText((int) (imageHeight() / (heightRatio() * 3)) + ""); } refreshStyle(splitOptionsBox); } catch (Exception e) { MyBoxLog.error(e); } } /* predeined */ @FXML protected void do42Action(ActionEvent event) { divideImageByNumber(4, 2); } @FXML protected void do24Action(ActionEvent event) { divideImageByNumber(2, 4); } @FXML protected void do41Action(ActionEvent event) { divideImageByNumber(4, 1); } @FXML protected void do14Action(ActionEvent event) { divideImageByNumber(1, 4); } @FXML protected void do43Action(ActionEvent event) { divideImageByNumber(4, 3); } @FXML protected void do34Action(ActionEvent event) { divideImageByNumber(3, 4); } @FXML protected void do44Action(ActionEvent event) { divideImageByNumber(4, 4); } @FXML protected void do13Action(ActionEvent event) { divideImageByNumber(1, 3); } @FXML protected void do31Action(ActionEvent event) { divideImageByNumber(3, 1); } @FXML protected void do12Action(ActionEvent event) { divideImageByNumber(1, 2); } @FXML protected void do21Action(ActionEvent event) { divideImageByNumber(2, 1); } @FXML protected void do32Action(ActionEvent event) { divideImageByNumber(3, 2); } @FXML protected void do23Action(ActionEvent event) { divideImageByNumber(2, 3); } @FXML protected void do22Action(ActionEvent event) { divideImageByNumber(2, 2); } @FXML protected void do33Action(ActionEvent event) { divideImageByNumber(3, 3); } /* by size */ protected void pickSize() { try { int v = Integer.parseInt(widthInput.getText()); if (v > 0 && v < operationWidth()) { widthInput.setStyle(null); width = v; } else { widthInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("Width")); return; } } catch (Exception e) { widthInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("Width")); return; } try { int v = Integer.parseInt(heightInput.getText()); if (v > 0 && v < operationHeight()) { heightInput.setStyle(null); height = v; } else { heightInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("Height")); return; } } catch (Exception e) { heightInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("Height")); return; } divideImageBySize(); } protected void divideImageBySize() { if (width <= 0 || height <= 0) { return; } try { cols = new ArrayList<>(); cols.add(0); int v = width; while (v < operationWidth()) { cols.add(v); v += width; } cols.add(operationWidth()); rows = new ArrayList<>(); rows.add(0); v = height; while (v < operationHeight()) { rows.add(v); v += height; } rows.add(operationHeight()); indicateSplit(); } catch (Exception e) { MyBoxLog.error(e); } } /* by number */ protected void divideImageByNumber(int rows, int cols) { try { rowsInput.setText(rows + ""); colsInput.setText(cols + ""); pickNumbers(); } catch (Exception e) { MyBoxLog.error(e); } } protected void pickNumbers() { if (checkNumberValues()) { divideImageByNumber(); } } protected boolean checkNumberValues() { try { int v = Integer.parseInt(rowsInput.getText()); if (v > 0) { rowsNumber = v; rowsInput.setStyle(null); } else { rowsInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("RowsNumber")); return false; } } catch (Exception e) { rowsInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("RowsNumber")); return false; } try { int v = Integer.parseInt(colsInput.getText()); if (v > 0) { colsNumber = v; colsInput.setStyle(null); } else { colsInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("ColumnsNumber")); return false; } } catch (Exception e) { colsInput.setStyle(UserConfig.badStyle()); popError(message("InvalidParameter") + ": " + message("ColumnsNumber")); return false; } return true; } protected void divideImageByNumber() { if (rowsNumber <= 0 || colsNumber <= 0) { return; } try { cols = new ArrayList<>(); cols.add(0); int w = (int) operationWidth(); for (int i = 1; i < colsNumber; ++i) { int v = i * w / colsNumber; cols.add(v); } cols.add(w); rows = new ArrayList<>(); rows.add(0); int h = (int) operationHeight(); for (int i = 1; i < rowsNumber; ++i) { int v = i * h / rowsNumber; rows.add(v); } rows.add(h); indicateSplit(); } catch (Exception e) { MyBoxLog.error(e); } } /* customize */ protected void pickCustomize() { try { boolean isValidRows = true, isValidcols = true; rows = new ArrayList<>(); rows.add(0); rows.add(operationHeight()); cols = new ArrayList<>(); cols.add(0); cols.add(operationWidth()); customizedRowsInput.setStyle(null); customizedColsInput.setStyle(null); if (!customizedRowsInput.getText().isEmpty()) { String[] rowStrings = customizedRowsInput.getText().split(","); for (String row : rowStrings) { try { int value = Integer.parseInt(row.trim()); if (value < 0 || value > operationHeight() - 1) { customizedRowsInput.setStyle(UserConfig.badStyle()); isValidRows = false; break; } if (!rows.contains(value)) { rows.add(value); } } catch (Exception e) { customizedRowsInput.setStyle(UserConfig.badStyle()); isValidRows = false; } } } if (!customizedColsInput.getText().isEmpty()) { String[] colStrings = customizedColsInput.getText().split(","); for (String col : colStrings) { try { int value = Integer.parseInt(col.trim()); if (value <= 0 || value >= operationWidth() - 1) { customizedColsInput.setStyle(UserConfig.badStyle()); isValidcols = false; break; } if (!cols.contains(value)) { cols.add(value); } } catch (Exception e) { customizedColsInput.setStyle(UserConfig.badStyle()); isValidcols = false; break; } } } if (!isValidRows) { popError(message("InvalidParameter") + ": " + message("SplittingRows")); } if (!isValidcols) { popError(message("InvalidParameter") + ": " + message("SplittingColumns")); } if (isValidRows && isValidcols) { indicateSplit(); } } catch (Exception e) { MyBoxLog.error(e); } } @FXML protected void clearRows() { customizedRowsInput.setText(""); } @FXML protected void clearCols() { customizedColsInput.setText(""); } /* handle */ @FXML @Override public void goAction() { try { switch (splitMethod) { case ByNumber: pickNumbers(); break; case BySize: pickSize(); break; case Customize: pickCustomize(); break; } } catch (Exception e) { MyBoxLog.debug(e); } } protected void initSplit() { try { List<Node> nodes = new ArrayList<>(); nodes.addAll(maskPane.getChildren()); for (Node node : nodes) { if (node != null && node.getId() != null && node.getId().startsWith("SplitLines")) { maskPane.getChildren().remove(node); } } imageView.setImage(image); sizeLabel.setText(""); imageInfos.clear(); } catch (Exception e) { MyBoxLog.error(e); } } protected void indicateSplit() { try { initSplit(); if (rows == null || cols == null || rows.size() < 2 || cols.size() < 2 || (rows.size() == 2 && cols.size() == 2)) { splitValid.set(false); return; } IntTools.sortList(rows); IntTools.sortList(cols); Color strokeColor = strokeColor(); double strokeWidth = strokeWidth(); double w = viewWidth(); double h = viewHeight(); double ratiox = viewXRatio() * widthRatio(); double ratioy = viewXRatio() * heightRatio(); for (int i = 0; i < rows.size(); ++i) { double row = rows.get(i) * ratioy; if (row <= 0 || row >= h - 1) { continue; } Line line = new Line(0, row, w, row); addLine(i, line, false, ratioy, strokeColor, strokeWidth); } for (int i = 0; i < cols.size(); ++i) { double col = cols.get(i) * ratiox; if (col <= 0 || col >= w - 1) { continue; } Line line = new Line(col, 0, col, h); addLine(i, line, true, ratiox, strokeColor, strokeWidth); } if (displaySizeCheck.isSelected()) { String style = " -fx-font-size: 1.2em; "; for (int i = 0; i < rows.size() - 1; ++i) { double row = rows.get(i) * ratioy; int hv = rows.get(i + 1) - rows.get(i); for (int j = 0; j < cols.size() - 1; ++j) { double col = cols.get(j) * ratiox; int wv = cols.get(j + 1) - cols.get(j); Text text = new Text(wv + "x" + hv); text.setStyle(style); text.setFill(strokeColor); text.setId("SplitLinesText" + i + "x" + j); text.setLayoutX(imageView.getLayoutX()); text.setLayoutY(imageView.getLayoutY()); text.setX(col + 10); text.setY(row + 10); maskPane.getChildren().add(text); } } } String comments = message("SplittedNumber") + ": " + (cols.size() - 1) * (rows.size() - 1); sizeLabel.setText(comments); splitValid.set(true); } catch (Exception e) { MyBoxLog.error(e); splitValid.set(false); } makeList(); } protected void addLine(int index, Line line, boolean isCol, double ratio, Color strokeColor, double strokeWidth) { if (isCol) { line.setId("SplitLinesCols" + index); } else { line.setId("SplitLinesRows" + index); } line.setStroke(strokeColor); line.setStrokeWidth(strokeWidth); line.getStrokeDashArray().clear(); line.getStrokeDashArray().addAll(strokeWidth, strokeWidth * 3); line.setLayoutX(imageView.getLayoutX()); line.setLayoutY(imageView.getLayoutY()); maskPane.getChildren().add(line); line.setCursor(defaultShapeCursor()); line.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { controlPressed(event); } }); line.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { } }); line.setOnMouseReleased(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { scrollPane.setPannable(true); double offsetX = imageOffsetX(event); double offsetY = imageOffsetY(event); if (!DoubleShape.changed(offsetX, offsetY)) { return; } if (isCol) { double x = event.getX(); line.setStartX(x); line.setEndX(x); cols.set(index, (int) (x / ratio)); } else { double y = event.getY(); line.setStartY(y); line.setEndY(y); rows.set(index, (int) (y / ratio)); } lineChanged(); } }); line.hoverProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue ov, Boolean oldValue, Boolean newValue) { if (newValue && popLineMenuCheck.isSelected()) { popNodeMenu(line, lineMenu(line, index, isCol, ratio)); } } }); } protected List<MenuItem> lineMenu(Line line, int index, boolean isCol, double ratio) { try { if (line == null) { return null; } List<MenuItem> items = new ArrayList<>(); MenuItem menu; int currentValue; String name, type; if (isCol) { name = message("Column"); type = "x"; currentValue = cols.get(index); } else { name = message("Row"); type = "y"; currentValue = rows.get(index); } menu = new MenuItem(name + " " + index + "\n" + type + ": " + currentValue); menu.setStyle(attributeTextStyle()); items.add(menu); items.add(new SeparatorMenuItem()); menu = new MenuItem(message("MoveTo"), StyleTools.getIconImageView("iconMove.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { String value = PopTools.askValue(baseTitle, name, type, currentValue + ""); if (value == null || value.isBlank()) { return; } try { int iv = Integer.parseInt(value); double vv = iv * ratio; if (isCol) { line.setStartX(vv); line.setEndX(vv); cols.set(index, iv); } else { line.setStartY(vv); line.setEndY(vv); rows.set(index, iv); } lineChanged(); } catch (Exception e) { popError(message("InvalidValue")); } }); items.add(menu); menu = new MenuItem(message("Delete"), StyleTools.getIconImageView("iconDelete.png")); menu.setOnAction((ActionEvent menuItemEvent) -> { if (isCol) { cols.remove(index); } else { rows.remove(index); } lineChanged(); }); items.add(menu); items.add(new SeparatorMenuItem()); return items; } catch (Exception e) { MyBoxLog.error(e); return null; } } protected void lineChanged() { try { customizeRadio.setSelected(true); String s = ""; for (int col : cols) { if (col <= 0 || col >= operationWidth()) { continue; } if (s.isEmpty()) { s += col; } else { s += "," + col; } } customizedColsInput.setText(s); s = ""; for (int row : rows) { if (row <= 0 || row >= operationHeight()) { continue; } if (s.isEmpty()) { s += row; } else { s += "," + row; } } customizedRowsInput.setText(s); indicateSplit(); } catch (Exception e) { MyBoxLog.error(e); } } public synchronized void makeList() { if (imageInfos == null) { return; } imageInfos.clear(); if (!splitValid.get()) { return; } try { int x1, y1, x2, y2; for (int i = 0; i < rows.size() - 1; ++i) { y1 = rows.get(i); y2 = rows.get(i + 1); for (int j = 0; j < cols.size() - 1; ++j) { x1 = cols.get(j); x2 = cols.get(j + 1); ImageInformation info; if (imageInformation != null) { info = imageInformation.cloneAttributes(); } else { info = new ImageInformation(image); } info.setRegion(x1, y1, x2, y2); imageInfos.add(info); } } } catch (Exception e) { MyBoxLog.debug(e); } } @Override public void imageSingleClicked(MouseEvent event, DoublePoint p) { if (image == null || splitMethod != SplitMethod.Customize || event.getButton() != MouseButton.SECONDARY) { return; } try { List<MenuItem> items = new ArrayList<>(); MenuItem menu; double px = scale(p.getX()); double py = scale(p.getY()); menu = new MenuItem(message("Point") + ": " + px + ", " + py); menu.setStyle(attributeTextStyle()); items.add(menu); items.add(new SeparatorMenuItem()); menu = new MenuItem(message("AddRowAtPoint"), StyleTools.getIconImageView("iconAdd.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { int y = (int) Math.round(p.getY() / heightRatio()); String str = customizedRowsInput.getText().trim(); if (str.isEmpty()) { customizedRowsInput.setText(y + ""); } else { customizedRowsInput.setText(str + "," + y); } pickCustomize(); } }); items.add(menu); menu = new MenuItem(message("AddColAtPoint"), StyleTools.getIconImageView("iconAdd.png")); menu.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent mevent) { int x = (int) Math.round(p.getX() / widthRatio()); String str = customizedColsInput.getText().trim(); if (str.isEmpty()) { customizedColsInput.setText(x + ""); } else { customizedColsInput.setText(str + "," + x); } pickCustomize(); } }); items.add(menu); items.add(new SeparatorMenuItem()); popEventMenu(event, items); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean redrawMaskShape() { super.redrawMaskShape(); indicateSplit(); return true; } @FXML @Override public void playAction() { if (imageInfos == null || imageInfos.isEmpty()) { popError(message("NoData")); return; } ImagesPlayController.playImages(imageInfos); } @FXML @Override public void saveAsAction() { if (imageInfos == null || imageInfos.isEmpty()) { popError(message("NoData")); return; } ImagesSaveController.saveImages(this, imageInfos); } @FXML @Override public void editFrames() { if (imageInfos == null || imageInfos.isEmpty()) { popError(message("NoData")); return; } ImagesEditorController.openImages(imageInfos); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BaseShapeController.java
released/MyBox/src/main/java/mara/mybox/controller/BaseShapeController.java
package mara.mybox.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import mara.mybox.dev.MyBoxLog; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-6-24 * @License Apache License Version 2.0 * */ public class BaseShapeController extends BaseShapeController_MouseEvents { @Override public void initControls() { try { super.initControls(); clearMask(); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void initMaskPane() { try { super.initMaskPane(); resetShapeOptions(); initMaskControls(); } catch (Exception e) { MyBoxLog.error(e); } } public void resetShapeOptions() { showAnchors = UserConfig.getBoolean(baseName + "ShowAnchor", true); popItemMenu = UserConfig.getBoolean(baseName + "ItemPopMenu", true); addPointWhenClick = UserConfig.getBoolean(baseName + "AddPointWhenLeftClick", true); String aShape = UserConfig.getString(baseName + "AnchorShape", "Rectangle"); if ("Circle".equals(aShape)) { anchorShape = AnchorShape.Circle; } else if ("Name".equals(aShape)) { anchorShape = AnchorShape.Name; } else { anchorShape = AnchorShape.Rectangle; } popShapeMenu = true; maskControlDragged = false; } public void initMaskControls() { try { if (anchorCheck != null) { anchorCheck.setSelected(UserConfig.getBoolean(baseName + "ShowAnchor", true)); anchorCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal) { UserConfig.setBoolean(baseName + "ShowAnchor", anchorCheck.isSelected()); showAnchors = anchorCheck.isSelected(); setMaskAnchorsStyle(); } }); } if (popAnchorMenuCheck != null) { popAnchorMenuCheck.setSelected(UserConfig.getBoolean(baseName + "ItemPopMenu", true)); popAnchorMenuCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal) { UserConfig.setBoolean(baseName + "ItemPopMenu", popAnchorMenuCheck.isSelected()); popItemMenu = popAnchorMenuCheck.isSelected(); } }); } if (popLineMenuCheck != null) { popLineMenuCheck.setSelected(UserConfig.getBoolean(baseName + "ItemPopMenu", true)); popLineMenuCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal) { UserConfig.setBoolean(baseName + "ItemPopMenu", popLineMenuCheck.isSelected()); popItemMenu = popLineMenuCheck.isSelected(); } }); } if (addPointCheck != null) { addPointCheck.setSelected(UserConfig.getBoolean(baseName + "AddPointWhenLeftClick", true)); addPointCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal) { addPointWhenClick = addPointCheck.isSelected(); if (!isSettingValues) { UserConfig.setBoolean(baseName + "AddPointWhenLeftClick", addPointCheck.isSelected()); } } }); } if (shapeCanMoveCheck != null) { shapeCanMoveCheck.setSelected(UserConfig.getBoolean(baseName + "ShapeCanMove", true)); shapeCanMoveCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean oldVal, Boolean newVal) { if (!isSettingValues) { UserConfig.setBoolean(baseName + "ShapeCanMove", shapeCanMoveCheck.isSelected()); } } }); } } catch (Exception e) { MyBoxLog.error(e); } } @Override public void viewSizeChanged(double change) { if (isSettingValues || change < sizeChangeAware || imageView == null || imageView.getImage() == null) { return; } refinePane(); redrawMaskShape(); notifySize(); } @Override public void setImageChanged(boolean imageChanged) { super.setImageChanged(imageChanged); if (imageChanged) { redrawMaskShape(); } } @Override protected String moreDisplayInfo() { if (maskRectangle != null && maskRectangle.isVisible() && maskRectangleData != null) { return Languages.message("SelectedSize") + ":" + (int) (maskRectangleData.getWidth() / widthRatio()) + "x" + (int) (maskRectangleData.getHeight() / heightRatio()); } else { return ""; } } @Override public boolean afterImageLoaded() { try { if (!super.afterImageLoaded() || image == null) { return false; } clearMask(); maskShapeChanged(); return true; } catch (Exception e) { MyBoxLog.debug(e); return false; } } @FXML @Override public void options() { ImageShapeOptionsController.open(this, true); } @Override public void cleanPane() { try { maskShapeChanged = null; maskShapeDataChanged = null; } catch (Exception e) { } super.cleanPane(); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BarcodeDecoderController.java
released/MyBox/src/main/java/mara/mybox/controller/BarcodeDecoderController.java
package mara.mybox.controller; import com.google.zxing.BinaryBitmap; import com.google.zxing.EncodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; import java.util.HashMap; import java.util.List; import javafx.embed.swing.SwingFXUtils; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.TextArea; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.tools.BarcodeTools.BarcodeType; import mara.mybox.tools.ByteTools; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2019-9-24 * @Description * @License Apache License Version 2.0 */ public class BarcodeDecoderController extends BaseImageController { protected BarcodeType codeType; @FXML protected ComboBox<String> typeSelecor; @FXML protected TextArea codeInput; public BarcodeDecoderController() { baseTitle = Languages.message("BarcodeDecoder"); } @Override public boolean afterImageLoaded() { codeInput.setText(""); return super.afterImageLoaded(); } @FXML @Override public void startAction() { if (imageView.getImage() == null) { return; } if (task != null) { task.cancel(); } task = new FxSingletonTask<Void>(this) { private Result result; @Override protected boolean handle() { try { LuminanceSource source = new BufferedImageLuminanceSource( SwingFXUtils.fromFXImage(imageView.getImage(), null)); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); result = new MultiFormatReader().decode(bitmap, hints); return result != null; } catch (Exception e) { error = e.toString(); return false; } } @Override protected void whenSucceeded() { String s = "---------" + Languages.message("Contents") + "---------\n" + result.getText() + "\n\n---------" + Languages.message("MetaData") + "---------\n" + Languages.message("Type") + ": " + result.getBarcodeFormat().name(); if (result.getResultMetadata() != null) { for (ResultMetadataType type : result.getResultMetadata().keySet()) { Object value = result.getResultMetadata().get(type); switch (type) { case PDF417_EXTRA_METADATA: // PDF417ResultMetadata pdf417meta // = (PDF417ResultMetadata) result.getResultMetadata().get(ResultMetadataType.PDF417_EXTRA_METADATA); break; case BYTE_SEGMENTS: s += "\n" + Languages.message("BYTE_SEGMENTS") + ": "; for (byte[] bytes : (List<byte[]>) value) { s += ByteTools.bytesToHexFormat(bytes) + " "; } break; default: s += "\n" + Languages.message(type.name()) + ": " + value; } } } result.getTimestamp(); codeInput.setText(s); } }; start(task); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/XmlEditorController.java
released/MyBox/src/main/java/mara/mybox/controller/XmlEditorController.java
package mara.mybox.controller; import java.io.File; import java.util.List; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.MenuItem; import javafx.scene.input.KeyEvent; import javafx.scene.layout.VBox; import mara.mybox.db.data.VisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.WindowTools; import mara.mybox.tools.XmlTools; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-4-30 * @License Apache License Version 2.0 */ public class XmlEditorController extends BaseDomEditorController { @FXML protected ControlXmlTree domController; @FXML protected VBox treeBox; public XmlEditorController() { baseTitle = message("XmlEditor"); TipsLabelKey = "XmlEditorTips"; typeName = "XML"; } @Override public void setFileType() { setFileType(VisitHistory.FileType.XML); } @Override public void initValues() { try { super.initValues(); domController.xmlEditor = this; } catch (Exception e) { MyBoxLog.error(e); } } @Override public String makeBlank() { String name = PopTools.askValue(getBaseTitle(), message("Create"), message("Root"), "data"); if (name == null || name.isBlank()) { return null; } return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<" + name + "></" + name + ">"; } @Override public String currentEncoding() { String encoding = domController.doc.getXmlEncoding(); if (encoding == null) { encoding = "utf-8"; } return encoding; } @Override public void openSavedFile(File file) { XmlEditorController.open(file); } @Override public void loadDom(String xml, boolean updated) { domController.makeTree(xml); domChanged(updated); } @Override public String textsByDom() { return XmlTools.transform(domController.doc); } @Override public void clearDom() { domController.clearTree(); domChanged(true); } @FXML @Override protected void options() { XmlOptionsController.open(); } @Override public void domMenuAction() { domController.showFunctionsMenu(null); } @Override protected List<MenuItem> helpMenus(Event event) { return HelpTools.xmlHelps(); } @FXML @Override protected void exampleAction() { File example = HelpTools.xmlExample(Languages.embedFileLang()); if (example != null && example.exists()) { sourceFileChanged(example); // loadTexts(TextFileTools.readTexts(null, example, Charset.forName("utf-8"))); } } @Override public boolean handleKeyEvent(KeyEvent event) { if (treeBox.isFocused() || treeBox.isFocusWithin()) { if (domController.handleKeyEvent(event)) { return true; } } if (super.handleKeyEvent(event)) { return true; } return domController.handleKeyEvent(event); } /* static */ public static XmlEditorController load(String xml) { try { XmlEditorController controller = (XmlEditorController) WindowTools.openStage(Fxmls.XmlEditorFxml); controller.writePanes(xml); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } public static XmlEditorController open(File file) { try { XmlEditorController controller = (XmlEditorController) WindowTools.openStage(Fxmls.XmlEditorFxml); controller.sourceFileChanged(file); controller.requestMouse(); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImageOptionsController.java
released/MyBox/src/main/java/mara/mybox/controller/ImageOptionsController.java
package mara.mybox.controller; import java.awt.RenderingHints; import java.sql.Connection; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.FlowPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import mara.mybox.db.DerbyBase; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.WindowTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.value.AppVariables; import static mara.mybox.value.AppVariables.ImageHints; import mara.mybox.value.Fxmls; import mara.mybox.value.ImageRenderHints; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2023-7-19 * @License Apache License Version 2.0 */ public class ImageOptionsController extends BaseChildController { protected BaseImageController imageController; @FXML protected FlowPane stepPane; @FXML protected ControlColorSet alphaColorSetController, rulerColorController, gridColorController; @FXML protected ComboBox<String> zoomStepSelector, decimalSelector, gridWidthSelector, gridIntervalSelector, gridOpacitySelector; @FXML protected ToggleGroup renderGroup, colorRenderGroup, pixelsInterGroup, alphaInterGroup, shapeAntiGroup, textAntiGroup, fontFmGroup, strokeGroup, ditherGroup; @FXML protected TextField thumbnailWidthInput, maxDemoInput; @FXML protected CheckBox renderCheck; @FXML protected VBox viewBox, renderBox; @FXML protected RadioButton renderDefaultRadio, renderQualityRadio, renderSpeedRadio, colorRenderDefaultRadio, colorRenderQualityRadio, colorRenderSpeedRadio, pInter9Radio, pInter4Radio, pInter1Radio, aInterDefaultRadio, aInterQualityRadio, aInterSpeedRadio, antiDefaultRadio, antiQualityRadio, antiSpeedRadio, tantiDefaultRadio, tantiOnRadio, tantiOffRadio, tantiGaspRadio, tantiLcdHrgbRadio, tantiLcdHbgrRadio, tantiLcdVrgbOnRadio, tantiLcdVbgrRadio, fmDefaultRadio, fmOnRadio, fmOffRadio, strokeDefaultRadio, strokeNormalizeRadio, strokePureRadio, ditherDefaultRadio, ditherOnRadio, ditherOffRadio; @FXML protected Label alphaLabel; public ImageOptionsController() { baseTitle = message("ImageOptions"); } @Override public void initControls() { try { super.initControls(); baseName = "ImageOptions"; initViewOptions(); initRenderOptions(); } catch (Exception e) { MyBoxLog.error(e); } } public void setParameters(BaseImageController parent) { try { if (parent == null) { close(); return; } imageController = parent; if (!viewBox.getChildren().contains(stepPane)) { viewBox.getChildren().add(0, stepPane); } imageController.zoomStep = UserConfig.getInt(imageController.baseName + "ZoomStep", 40); imageController.zoomStep = imageController.zoomStep <= 0 ? 40 : imageController.zoomStep; imageController.xZoomStep = imageController.zoomStep; imageController.yZoomStep = imageController.zoomStep; zoomStepSelector.setValue(imageController.zoomStep + ""); zoomStepSelector.getItems().addAll( Arrays.asList("40", "20", "5", "1", "3", "15", "30", "50", "80", "100", "150", "200", "300", "500") ); zoomStepSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> ov, String oldVal, String newVal) { if (isSettingValues) { return; } try { int v = Integer.parseInt(newVal); if (v > 0) { imageController.zoomStep = v; UserConfig.setInt(imageController.baseName + "ZoomStep", imageController.zoomStep); zoomStepSelector.getEditor().setStyle(null); imageController.zoomStepChanged(); } else { zoomStepSelector.getEditor().setStyle(UserConfig.badStyle()); } } catch (Exception e) { zoomStepSelector.getEditor().setStyle(UserConfig.badStyle()); } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void initViewOptions() { try { viewBox.getChildren().remove(stepPane); rulerColorController.init(this, "RulerColor", Color.RED); rulerColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (isSettingValues) { return; } BaseImageController.updateMaskRulerXY(); } }); gridColorController.init(this, "GridLinesColor", Color.LIGHTGRAY); gridColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (isSettingValues) { return; } BaseImageController.updateMaskGrid(); } }); gridWidthSelector.getItems().addAll(Arrays.asList("2", "1", "3", "4", "5", "6", "7", "8", "9", "10")); int v = UserConfig.getInt("GridLinesWidth", 1); if (v <= 0) { v = 1; } gridWidthSelector.setValue(v + ""); gridWidthSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (isSettingValues || newValue == null || newValue.isEmpty()) { return; } try { int v = Integer.parseInt(newValue); if (v > 0) { UserConfig.setInt("GridLinesWidth", v); ValidationTools.setEditorNormal(gridWidthSelector); BaseImageController.updateMaskGrid(); } else { ValidationTools.setEditorBadStyle(gridWidthSelector); } } catch (Exception e) { ValidationTools.setEditorBadStyle(gridWidthSelector); } } }); gridIntervalSelector.getItems().addAll(Arrays.asList(message("Automatic"), "10", "20", "25", "50", "100", "5", "1", "2", "200", "500")); v = UserConfig.getInt("GridLinesInterval", -1); gridIntervalSelector.setValue(v <= 0 ? message("Automatic") : (v + "")); gridIntervalSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (isSettingValues || newValue == null || newValue.isEmpty()) { return; } int v = -1; try { if (!message("Automatic").equals(newValue)) { v = Integer.parseInt(newValue); } } catch (Exception e) { } UserConfig.setInt("GridLinesInterval", v); BaseImageController.updateMaskGrid(); } }); gridOpacitySelector.getItems().addAll(Arrays.asList("0.5", "0.2", "1.0", "0.7", "0.1", "0.3", "0.8", "0.9", "0.6", "0.4")); float f = UserConfig.getFloat("GridLinesOpacity", 0.1f); if (f < 0) { f = 0.1f; } gridOpacitySelector.setValue(f + ""); gridOpacitySelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (isSettingValues || newValue == null || newValue.isEmpty()) { return; } float v = 0.1f; try { v = Float.parseFloat(newValue); } catch (Exception e) { } UserConfig.setFloat("GridLinesOpacity", v); BaseImageController.updateMaskGrid(); } }); decimalSelector.getItems().addAll(Arrays.asList("2", "1", "3", "0", "4", "5", "6", "7", "8")); v = UserConfig.imageScale(); if (v < 0) { v = 0; } decimalSelector.setValue(v + ""); decimalSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (isSettingValues || newValue == null || newValue.isEmpty()) { return; } try { int v = Integer.parseInt(newValue); if (v > 0) { UserConfig.setInt("ImageDecimal", v); ValidationTools.setEditorNormal(decimalSelector); } else { ValidationTools.setEditorBadStyle(decimalSelector); } } catch (Exception e) { ValidationTools.setEditorBadStyle(decimalSelector); } } }); alphaColorSetController.init(this, "AlphaAsColor", Color.WHITE); alphaColorSetController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { if (!Color.WHITE.equals(alphaColorSetController.color())) { alphaLabel.setText(message("AlphaReplaceComments")); alphaLabel.setStyle(NodeStyleTools.darkRedTextStyle()); } else { alphaLabel.setText(""); } } }); thumbnailWidthInput.setText(AppVariables.thumbnailWidth + ""); thumbnailWidthInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { int v = Integer.parseInt(thumbnailWidthInput.getText()); if (v > 0) { UserConfig.setInt("ThumbnailWidth", v); AppVariables.thumbnailWidth = v; thumbnailWidthInput.setStyle(null); } else { thumbnailWidthInput.setStyle(UserConfig.badStyle()); } } catch (Exception e) { thumbnailWidthInput.setStyle(UserConfig.badStyle()); } } }); maxDemoInput.setText(AppVariables.maxDemoImage + ""); maxDemoInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { long v = Long.parseLong(maxDemoInput.getText()); if (v > 0) { UserConfig.setLong("MaxDemoImage", v); AppVariables.maxDemoImage = v; maxDemoInput.setStyle(null); } else { maxDemoInput.setStyle(UserConfig.badStyle()); } } catch (Exception e) { maxDemoInput.setStyle(UserConfig.badStyle()); } } }); } catch (Exception e) { MyBoxLog.error(e); } } public void initRenderOptions() { try { renderCheck.setSelected(ImageRenderHints.applyHints()); renderCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (isSettingValues) { return; } ImageRenderHints.applyHints(renderCheck.isSelected()); checkHints(); } }); renderBox.disableProperty().bind(renderCheck.selectedProperty().not()); applyHints(); renderGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { writeHints(); } }); colorRenderGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { writeHints(); } }); pixelsInterGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { writeHints(); } }); alphaInterGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { writeHints(); } }); shapeAntiGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { writeHints(); } }); textAntiGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { writeHints(); } }); fontFmGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { writeHints(); } }); strokeGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { writeHints(); } }); ditherGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> v, Toggle ov, Toggle nv) { writeHints(); } }); checkHints(); } catch (Exception e) { MyBoxLog.error(e); } } public void checkHints() { if (isSettingValues) { return; } if (ImageRenderHints.applyHints()) { writeHints(); } else { ImageHints = null; } } public synchronized void applyHints() { try { if (ImageHints == null) { return; } isSettingValues = true; renderCheck.setSelected(ImageRenderHints.applyHints()); Object render = ImageHints.get(RenderingHints.KEY_RENDERING); if (RenderingHints.VALUE_RENDER_QUALITY.equals(render)) { renderQualityRadio.setSelected(true); } else if (RenderingHints.VALUE_RENDER_SPEED.equals(render)) { renderSpeedRadio.setSelected(true); } else { renderDefaultRadio.setSelected(true); } Object crender = ImageHints.get(RenderingHints.KEY_COLOR_RENDERING); if (RenderingHints.VALUE_COLOR_RENDER_QUALITY.equals(crender)) { colorRenderQualityRadio.setSelected(true); } else if (RenderingHints.VALUE_COLOR_RENDER_SPEED.equals(crender)) { colorRenderSpeedRadio.setSelected(true); } else { colorRenderDefaultRadio.setSelected(true); } Object pinter = ImageHints.get(RenderingHints.KEY_INTERPOLATION); if (RenderingHints.VALUE_INTERPOLATION_BILINEAR.equals(pinter)) { pInter4Radio.setSelected(true); } else if (RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR.equals(pinter)) { pInter1Radio.setSelected(true); } else { pInter9Radio.setSelected(true); } Object ainter = ImageHints.get(RenderingHints.KEY_ALPHA_INTERPOLATION); if (RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY.equals(ainter)) { aInterQualityRadio.setSelected(true); } else if (RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED.equals(ainter)) { aInterSpeedRadio.setSelected(true); } else { aInterDefaultRadio.setSelected(true); } Object anti = ImageHints.get(RenderingHints.KEY_ANTIALIASING); if (RenderingHints.VALUE_ANTIALIAS_ON.equals(anti)) { antiQualityRadio.setSelected(true); } else if (RenderingHints.VALUE_ANTIALIAS_OFF.equals(anti)) { antiSpeedRadio.setSelected(true); } else { antiDefaultRadio.setSelected(true); } Object tanti = ImageHints.get(RenderingHints.KEY_TEXT_ANTIALIASING); if (RenderingHints.VALUE_TEXT_ANTIALIAS_ON.equals(tanti)) { tantiOnRadio.setSelected(true); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_OFF.equals(tanti)) { tantiOffRadio.setSelected(true); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_GASP.equals(tanti)) { tantiGaspRadio.setSelected(true); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB.equals(tanti)) { tantiLcdHrgbRadio.setSelected(true); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR.equals(tanti)) { tantiLcdHbgrRadio.setSelected(true); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB.equals(tanti)) { tantiLcdVrgbOnRadio.setSelected(true); } else if (RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR.equals(tanti)) { tantiLcdVbgrRadio.setSelected(true); } else { tantiDefaultRadio.setSelected(true); } Object fontfm = ImageHints.get(RenderingHints.KEY_FRACTIONALMETRICS); if (RenderingHints.VALUE_FRACTIONALMETRICS_ON.equals(fontfm)) { fmOnRadio.setSelected(true); } else if (RenderingHints.VALUE_FRACTIONALMETRICS_OFF.equals(fontfm)) { fmOffRadio.setSelected(true); } else { fmDefaultRadio.setSelected(true); } Object stroke = ImageHints.get(RenderingHints.KEY_STROKE_CONTROL); if (RenderingHints.VALUE_STROKE_NORMALIZE.equals(stroke)) { strokeNormalizeRadio.setSelected(true); } else if (RenderingHints.VALUE_STROKE_PURE.equals(stroke)) { strokePureRadio.setSelected(true); } else { strokeDefaultRadio.setSelected(true); } Object dither = ImageHints.get(RenderingHints.KEY_DITHERING); if (RenderingHints.VALUE_DITHER_ENABLE.equals(dither)) { ditherOnRadio.setSelected(true); } else if (RenderingHints.VALUE_DITHER_DISABLE.equals(dither)) { ditherOffRadio.setSelected(true); } else { ditherDefaultRadio.setSelected(true); } isSettingValues = false; } catch (Exception e) { MyBoxLog.error(e); } } public Map<RenderingHints.Key, Object> writeHints() { try { if (isSettingValues) { return ImageHints; } if (!ImageRenderHints.applyHints()) { ImageHints = null; return null; } ImageHints = new HashMap<>(); if (renderQualityRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); } else if (renderSpeedRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); } else { ImageHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_DEFAULT); } if (colorRenderQualityRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); } else if (colorRenderSpeedRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); } else { ImageHints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_DEFAULT); } if (pInter4Radio.isSelected()) { ImageHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } else if (pInter1Radio.isSelected()) { ImageHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } else { ImageHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); } if (aInterQualityRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); } else if (aInterSpeedRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED); } else { ImageHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT); } if (antiQualityRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } else if (antiSpeedRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); } else { ImageHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_DEFAULT); } if (tantiOnRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } else if (tantiOffRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } else if (tantiGaspRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP); } else if (tantiLcdHrgbRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); } else if (tantiLcdHbgrRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR); } else if (tantiLcdVrgbOnRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB); } else if (tantiLcdVbgrRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR); } else { ImageHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT); } if (fmOnRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } else if (fmOffRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF); } else { ImageHints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT); } if (strokeNormalizeRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); } else if (strokePureRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); } else { ImageHints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT); } if (ditherOnRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE); } else if (ditherOffRadio.isSelected()) { ImageHints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); } else { ImageHints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DEFAULT); } try (Connection conn = DerbyBase.getConnection()) { ImageRenderHints.saveImageRenderHints(conn); } catch (Exception e) { MyBoxLog.error(e); } return ImageHints; } catch (Exception e) { MyBoxLog.error(e); return null; } } @FXML public void aboutRenderHints() { openLink(HelpTools.renderingHintsLink()); } /* static methods */ public static ImageOptionsController open(BaseImageController parent) { try { if (parent == null) { return null; } ImageOptionsController controller = (ImageOptionsController) WindowTools.referredTopStage( parent, Fxmls.ImageOptionsFxml); controller.setParameters(parent); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ImageSmoothBatchController.java
released/MyBox/src/main/java/mara/mybox/controller/ImageSmoothBatchController.java
package mara.mybox.controller; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import javafx.fxml.FXML; import mara.mybox.image.data.ImageConvolution; import mara.mybox.db.data.ConvolutionKernel; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.image.PixelDemos; import mara.mybox.fxml.FxTask; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2018-9-23 * @License Apache License Version 2.0 */ public class ImageSmoothBatchController extends BaseImageEditBatchController { protected ConvolutionKernel kernel; @FXML protected ControlImageSmooth smoothController; public ImageSmoothBatchController() { baseTitle = message("ImageBatch") + " - " + message("Smooth"); } @Override public boolean makeMoreParameters() { if (!super.makeMoreParameters()) { return false; } kernel = smoothController.pickValues(); return kernel != null; } @Override protected BufferedImage handleImage(FxTask currentTask, BufferedImage source) { try { return ImageConvolution.create() .setImage(source).setKernel(kernel) .setTask(currentTask) .start(); } catch (Exception e) { MyBoxLog.error(e); return null; } } @Override public void makeDemoFiles(FxTask currentTask, List<String> files, File demoFile, BufferedImage demoImage) { try { ImageConvolution convolution = ImageConvolution.create() .setImage(demoImage); PixelDemos.smooth(currentTask, files, convolution, demoFile); } catch (Exception e) { MyBoxLog.error(e.toString()); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/SettingsController.java
released/MyBox/src/main/java/mara/mybox/controller/SettingsController.java
package mara.mybox.controller; import com.sun.management.OperatingSystemMXBean; import java.io.File; import java.lang.management.ManagementFactory; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.RadioButton; import javafx.scene.control.Tab; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.DirectoryChooser; import javafx.stage.Window; import mara.mybox.MyBox; import mara.mybox.db.Database; import mara.mybox.db.DerbyBase; import mara.mybox.db.DerbyBase.DerbyStatus; import mara.mybox.db.table.TableVisitHistory; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.PopTools; import mara.mybox.fxml.ValidationTools; import mara.mybox.fxml.WindowTools; import static mara.mybox.fxml.WindowTools.refreshInterfaceAll; import static mara.mybox.fxml.WindowTools.reloadAll; import static mara.mybox.fxml.WindowTools.styleAll; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.fxml.style.StyleTools; import mara.mybox.tools.ConfigTools; import mara.mybox.tools.FileCopyTools; import mara.mybox.tools.FileDeleteTools; import mara.mybox.value.AppValues; import mara.mybox.value.AppVariables; import mara.mybox.value.Colors; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2018-10-14 * @Description * @License Apache License Version 2.0 */ public class SettingsController extends BaseController { protected int recentFileNumber, newJVM; @FXML protected Tab interfaceTab, baseTab, dataTab, mapTab; @FXML protected ToggleGroup langGroup, controlColorGroup, derbyGroup, splitPanesGroup; @FXML protected CheckBox closeCurrentCheck, operationWindowIconifyParentCheck, recordWindowsSizeLocationCheck, clearExpiredCheck, controlsTextCheck, shortcutsCanNotOmitCheck, icons40pxCheck, lostFocusCommitCheck, copyCurrentDataPathCheck, clearCurrentRootCheck, stopAlarmCheck; @FXML protected TextField jvmInput, dataDirInput, batchInput, fileRecentInput, tiandituWebKeyInput, gaodeWebKeyInput, gaodeServiceKeyInput, webConnectTimeoutInput, webReadTimeoutInput; @FXML protected VBox localBox, dataBox; @FXML protected ComboBox<String> fontSizeBox, iconSizeBox, scrollSizeSelector, popSizeSelector, popDurationSelector; @FXML protected HBox imageHisBox, derbyBox; @FXML protected Button settingsRecentOKButton, settingsChangeRootButton, settingsDataPathButton, settingsJVMButton; @FXML protected RadioButton chineseRadio, englishRadio, embeddedRadio, networkRadio, redRadio, orangeRadio, pinkRadio, lightBlueRadio, blueRadio, greenRadio, colorCustomizeRadio; @FXML protected Rectangle colorCustomizeRect; @FXML protected ControlColorSet popBgColorController, popInfoColorController, popErrorColorController, popWarnColorController; @FXML protected ListView languageList; @FXML protected Label currentJvmLabel, currentDataPathLabel, currentTempPathLabel, derbyStatus; public SettingsController() { baseTitle = message("Settings"); } @Override public void initControls() { try { super.initControls(); initInterfaceTab(); initBaseTab(); initDataTab(); initMapTab(); } catch (Exception e) { MyBoxLog.debug(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); isSettingValues = true; initSettingValues(); isSettingValues = false; NodeStyleTools.setTooltip(redRadio, new Tooltip(message("MyBoxColorRedDark"))); NodeStyleTools.setTooltip(pinkRadio, new Tooltip(message("MyBoxColorPinkDark"))); NodeStyleTools.setTooltip(orangeRadio, new Tooltip(message("MyBoxColorOrangeDark"))); NodeStyleTools.setTooltip(lightBlueRadio, new Tooltip(message("MyBoxColorLightBlueDark"))); NodeStyleTools.setTooltip(blueRadio, new Tooltip(message("MyBoxColorBlueDark"))); NodeStyleTools.setTooltip(greenRadio, new Tooltip(message("MyBoxColorGreenDark"))); NodeStyleTools.setTooltip(colorCustomizeRadio, new Tooltip(message("Customize"))); NodeStyleTools.setTooltip(imageHisBox, new Tooltip(message("ImageHisComments"))); colorCustomizeRect.setFill(Colors.customizeColorDark()); } catch (Exception e) { MyBoxLog.debug(e); } } protected void initSettingValues() { try { clearExpiredCheck.setSelected(UserConfig.getBoolean("ClearExpiredDataBeforeExit", true)); stopAlarmCheck.setSelected(UserConfig.getBoolean("StopAlarmsWhenExit")); closeCurrentCheck.setSelected(AppVariables.closeCurrentWhenOpenTool); operationWindowIconifyParentCheck.setSelected(AppVariables.operationWindowIconifyParent); recentFileNumber = UserConfig.getInt("FileRecentNumber", 20); fileRecentInput.setText(recentFileNumber + ""); switch (AppVariables.ControlColor) { case Pink: pinkRadio.setSelected(true); break; case Blue: blueRadio.setSelected(true); break; case LightBlue: lightBlueRadio.setSelected(true); break; case Orange: orangeRadio.setSelected(true); break; case Green: greenRadio.setSelected(true); break; case Customize: colorCustomizeRadio.setSelected(true); break; default: redRadio.setSelected(true); } controlsTextCheck.setSelected(AppVariables.controlDisplayText); icons40pxCheck.setSelected(AppVariables.icons40px); shortcutsCanNotOmitCheck.setSelected(AppVariables.ShortcutsCanNotOmitCtrlAlt); lostFocusCommitCheck.setSelected(AppVariables.commitModificationWhenDataCellLoseFocus); checkLanguage(); } catch (Exception e) { MyBoxLog.debug(e); } } /* Interface settings */ public void initInterfaceTab() { try { langGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkLanguage(); } }); fontSizeBox.getItems().addAll(Arrays.asList( "9", "10", "12", "14", "15", "16", "17", "18", "19", "20", "21", "22") ); fontSizeBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (newValue != null && !newValue.isEmpty()) { try { int v = Integer.parseInt(newValue); if (v > 0) { setSceneFontSize(v); ValidationTools.setEditorNormal(fontSizeBox); } else { ValidationTools.setEditorBadStyle(fontSizeBox); } } catch (Exception e) { ValidationTools.setEditorBadStyle(fontSizeBox); } } } }); fontSizeBox.getSelectionModel().select(AppVariables.sceneFontSize + ""); iconSizeBox.getItems().addAll(Arrays.asList( "20", "15", "25", "18", "22", "12", "10") ); iconSizeBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (newValue != null && !newValue.isEmpty()) { try { int v = Integer.parseInt(newValue); if (v > 0) { setIconSize(v); ValidationTools.setEditorNormal(iconSizeBox); } else { ValidationTools.setEditorBadStyle(iconSizeBox); } } catch (Exception e) { ValidationTools.setEditorBadStyle(iconSizeBox); } } } }); iconSizeBox.getSelectionModel().select(AppVariables.iconSize + ""); closeCurrentCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { UserConfig.setBoolean("CloseCurrentWhenOpenTool", closeCurrentCheck.isSelected()); AppVariables.closeCurrentWhenOpenTool = closeCurrentCheck.isSelected(); } }); operationWindowIconifyParentCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { UserConfig.setBoolean("OperationWindowIconifyParent", operationWindowIconifyParentCheck.isSelected()); AppVariables.operationWindowIconifyParent = operationWindowIconifyParentCheck.isSelected(); } }); recordWindowsSizeLocationCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { UserConfig.setBoolean("RecordWindowsSizeLocation", recordWindowsSizeLocationCheck.isSelected()); AppVariables.recordWindowsSizeLocation = recordWindowsSizeLocationCheck.isSelected(); } }); controlColorGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) { checkControlsColor(); } }); controlsTextCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { if (isSettingValues) { return; } AppVariables.controlDisplayText = controlsTextCheck.isSelected(); UserConfig.setBoolean("ControlDisplayText", AppVariables.controlDisplayText); refreshInterfaceAll(); } }); lostFocusCommitCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { if (isSettingValues) { return; } AppVariables.lostFocusCommitData(lostFocusCommitCheck.isSelected()); } }); icons40pxCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { if (isSettingValues) { return; } AppVariables.icons40px = icons40pxCheck.isSelected(); UserConfig.setBoolean("Icons40px", AppVariables.icons40px); refreshInterfaceAll(); } }); popSizeSelector.getItems().addAll(Arrays.asList( "1.5", "1", "1.2", "2", "2.5", "0.8") ); popSizeSelector.setValue(UserConfig.getString("PopTextSize", "1.5")); popSizeSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (newValue != null && !newValue.isEmpty()) { try { float f = Float.parseFloat(newValue); if (f > 0) { UserConfig.setString("PopTextSize", newValue); ValidationTools.setEditorNormal(popSizeSelector); popSuccessful(); } else { ValidationTools.setEditorBadStyle(popSizeSelector); } } catch (Exception e) { ValidationTools.setEditorBadStyle(popSizeSelector); } } } }); popDurationSelector.getItems().addAll(Arrays.asList( "3000", "5000", "2000", "1500", "1000", "4000", "2500") ); popDurationSelector.setValue(UserConfig.getInt("PopTextDuration", 3000) + ""); popDurationSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (newValue != null && !newValue.isEmpty()) { try { int v = Integer.parseInt(newValue); if (v > 0) { UserConfig.setInt("PopTextDuration", v); ValidationTools.setEditorNormal(popDurationSelector); popSuccessful(); } else { ValidationTools.setEditorBadStyle(popDurationSelector); } } catch (Exception e) { ValidationTools.setEditorBadStyle(popDurationSelector); } } } }); popBgColorController.init(this, "PopTextBgColor", Color.BLACK); popBgColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setString("PopTextBgColor", popBgColorController.css()); popSuccessful(); } }); popInfoColorController.init(this, "PopInfoColor", Color.WHITE); popInfoColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setString("PopInfoColor", popInfoColorController.css()); popSuccessful(); } }); popErrorColorController.init(this, "PopErrorColor", Color.AQUA); popErrorColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setString("PopErrorColor", popErrorColorController.css()); popSuccessful(); } }); popWarnColorController.init(this, "PopWarnColor", Color.ORANGE); popWarnColorController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { UserConfig.setString("PopWarnColor", popWarnColorController.css()); popSuccessful(); } }); scrollSizeSelector.getItems().addAll(Arrays.asList( "100", "500", "1000", "20", "50", "200", Integer.MAX_VALUE + "") ); scrollSizeSelector.setValue(UserConfig.selectorScrollSize() + ""); scrollSizeSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> vv, String ov, String nv) { if (nv != null && !nv.isEmpty()) { try { int v = Integer.parseInt(nv); if (v > 0) { UserConfig.setInt("SelectorScrollSize", v); ValidationTools.setEditorNormal(scrollSizeSelector); } else { ValidationTools.setEditorBadStyle(scrollSizeSelector); } } catch (Exception e) { ValidationTools.setEditorBadStyle(scrollSizeSelector); } } } }); } catch (Exception e) { MyBoxLog.debug(e); } } protected void checkLanguage() { if (AppVariables.CurrentBundle == Languages.BundleZhCN) { chineseRadio.setSelected(true); } else { englishRadio.setSelected(true); } } protected void checkControlsColor() { try { if (isSettingValues) { return; } if (pinkRadio.isSelected()) { StyleTools.setConfigStyleColor(this, "Pink"); } else if (lightBlueRadio.isSelected()) { StyleTools.setConfigStyleColor(this, "LightBlue"); } else if (blueRadio.isSelected()) { StyleTools.setConfigStyleColor(this, "Blue"); } else if (orangeRadio.isSelected()) { StyleTools.setConfigStyleColor(this, "Orange"); } else if (greenRadio.isSelected()) { StyleTools.setConfigStyleColor(this, "Green"); } else if (colorCustomizeRadio.isSelected()) { StyleTools.setConfigStyleColor(this, "Customize"); } else { StyleTools.setConfigStyleColor(this, "Red"); } } catch (Exception e) { MyBoxLog.error(e); } } public void setStyle(String style) { try { UserConfig.setString("InterfaceStyle", style); styleAll(style); } catch (Exception e) { // MyBoxLog.error(e); } } @FXML protected void setChinese(ActionEvent event) { Languages.setLanguage("zh"); reloadAll(); } @FXML protected void setEnglish(ActionEvent event) { Languages.setLanguage("en"); reloadAll(); } @FXML protected void shortcutsCanNotOmit() { AppVariables.ShortcutsCanNotOmitCtrlAlt = shortcutsCanNotOmitCheck.isSelected(); UserConfig.setBoolean("ShortcutsCanNotOmitCtrlAlt", AppVariables.ShortcutsCanNotOmitCtrlAlt); } @FXML protected void inputColorAction() { SettingCustomColorsController.open(this); } /* Base settings */ public void initBaseTab() { try { int mb = 1024 * 1024; OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); final long totalM = osmxb.getTotalMemorySize() / mb; String m = message("PhysicalMemory") + ": " + totalM + "MB"; Runtime r = Runtime.getRuntime(); final long jvmM = r.maxMemory() / mb; m += " " + message("JvmXmx") + ": " + jvmM + "MB"; currentJvmLabel.setText(m); jvmInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (isSettingValues) { return; } try { int v = Integer.parseInt(jvmInput.getText()); if (v > 50 && v <= totalM - 50) { jvmInput.setStyle(null); if (jvmM == v) { settingsJVMButton.setDisable(true); return; } newJVM = v; settingsJVMButton.setDisable(false); } else { jvmInput.setStyle(UserConfig.badStyle()); settingsJVMButton.setDisable(true); } } catch (Exception e) { jvmInput.setStyle(UserConfig.badStyle()); settingsJVMButton.setDisable(true); } } }); isSettingValues = true; jvmInput.setText(jvmM + ""); settingsJVMButton.setDisable(true); isSettingValues = false; webConnectTimeoutInput.setText(UserConfig.getInt("WebConnectTimeout", 10000) + ""); webReadTimeoutInput.setText(UserConfig.getInt("WebReadTimeout", 10000) + ""); } catch (Exception e) { MyBoxLog.debug(e); } } @FXML protected void setJVM() { Platform.runLater(new Runnable() { @Override public void run() { try { long defaultJVM = Runtime.getRuntime().maxMemory() / (1024 * 1024); if (newJVM == defaultJVM) { ConfigTools.writeConfigValue("JVMmemory", null); } else { ConfigTools.writeConfigValue("JVMmemory", "-Xms" + newJVM + "m"); } MyBox.restart(); } catch (Exception e) { MyBoxLog.debug(e); } } }); } @FXML protected void defaultJVM() { OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); long defaultJVM = osmxb.getTotalMemorySize() / (4 * 1024 * 1024); jvmInput.setText(defaultJVM + ""); } @FXML protected void okWebConnectTimeout() { try { int v = Integer.parseInt(webConnectTimeoutInput.getText()); if (v > 0) { UserConfig.setInt("WebConnectTimeout", v); webConnectTimeoutInput.setStyle(null); popSuccessful(); } else { webConnectTimeoutInput.setStyle(UserConfig.badStyle()); } } catch (Exception e) { webConnectTimeoutInput.setStyle(UserConfig.badStyle()); } } @FXML protected void okWebReadTimeout() { try { int v = Integer.parseInt(webReadTimeoutInput.getText()); if (v > 0) { UserConfig.setInt("WebReadTimeout", v); webReadTimeoutInput.setStyle(null); popSuccessful(); } else { webReadTimeoutInput.setStyle(UserConfig.badStyle()); } } catch (Exception e) { webReadTimeoutInput.setStyle(UserConfig.badStyle()); } } /* Data settings */ public void initDataTab() { try { fileRecentInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { checkRecentFile(); } }); dataDirInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { String p = dataDirInput.getText(); if (isSettingValues || p == null || p.trim().isEmpty() || p.trim().equals(AppVariables.MyboxDataPath)) { settingsChangeRootButton.setDisable(true); return; } settingsChangeRootButton.setDisable(false); } }); dataDirInput.setText(AppVariables.MyboxDataPath); currentDataPathLabel.setText(MessageFormat.format(message("CurrentValue"), AppVariables.MyboxDataPath)); clearCurrentRootCheck.setText(MessageFormat.format(message("ClearPathWhenChange"), AppVariables.MyboxDataPath)); setDerbyMode(); derbyGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue ov, Toggle old_val, Toggle new_val) { checkDerbyMode(); } }); batchInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (isSettingValues) { return; } try { long v = Long.parseLong(batchInput.getText()); if (v > 0) { batchInput.setStyle(null); Database.BatchSize = v; UserConfig.setLong("DatabaseBatchSize", v); } else { batchInput.setStyle(UserConfig.badStyle()); } } catch (Exception e) { batchInput.setStyle(UserConfig.badStyle()); } } }); batchInput.setText(Database.BatchSize + ""); clearExpiredCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { UserConfig.setBoolean("ClearExpiredDataBeforeExit", clearExpiredCheck.isSelected()); } }); stopAlarmCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { UserConfig.setBoolean("StopAlarmsWhenExit", stopAlarmCheck.isSelected()); } }); } catch (Exception e) { MyBoxLog.debug(e); } } @FXML protected void selectDataPath(ActionEvent event) { try { DirectoryChooser chooser = new DirectoryChooser(); chooser.setInitialDirectory(new File(AppVariables.MyboxDataPath)); File directory = chooser.showDialog(getMyStage()); if (directory == null) { return; } recordFileWritten(directory); dataDirInput.setText(directory.getPath()); } catch (Exception e) { MyBoxLog.error(e); } } @FXML protected void changeDataPath(ActionEvent event) { try { String newPath = dataDirInput.getText(); if (isSettingValues || newPath == null || newPath.trim().isEmpty() || newPath.trim().equals(AppVariables.MyboxDataPath)) { return; } String oldPath = AppVariables.MyboxDataPath; if (copyCurrentDataPathCheck.isSelected()) { if (!PopTools.askSure(getTitle(), message("ChangeDataPathConfirm"))) { return; } popInformation(message("CopyingFilesFromTo")); if (FileCopyTools.copyWholeDirectory(null, new File(oldPath), new File(newPath), null, false)) { File lckFile = new File(newPath + File.separator + "mybox_derby" + File.separator + "db.lck"); if (lckFile.exists()) { try { FileDeleteTools.delete(lckFile); } catch (Exception e) { MyBoxLog.error(e); } } } else { popFailed(); dataDirInput.setStyle(UserConfig.badStyle()); } } AppVariables.MyboxDataPath = newPath; ConfigTools.writeConfigValue("MyBoxDataPath", newPath); dataDirInput.setStyle(null); if (clearCurrentRootCheck.isSelected()) { ConfigTools.writeConfigValue("MyBoxOldDataPath", oldPath); } MyBox.restart(); } catch (Exception e) { popFailed(); dataDirInput.setStyle(UserConfig.badStyle()); } } @FXML protected void setFileRecentAction(ActionEvent event) { UserConfig.setInt("FileRecentNumber", recentFileNumber); AppVariables.fileRecentNumber = recentFileNumber; popSuccessful(); } @FXML protected void clearFileHistories(ActionEvent event) { if (!PopTools.askSure(getTitle(), message("SureClear"))) { return; } new TableVisitHistory().clear(); popSuccessful(); } private void checkRecentFile() { try { int v = Integer.parseInt(fileRecentInput.getText()); if (v >= 0) { recentFileNumber = v; fileRecentInput.setStyle(null); settingsRecentOKButton.setDisable(false); } else { fileRecentInput.setStyle(UserConfig.badStyle()); settingsRecentOKButton.setDisable(true); } } catch (Exception e) { fileRecentInput.setStyle(UserConfig.badStyle()); settingsRecentOKButton.setDisable(true); } } public void setDerbyMode() { isSettingValues = true; if (DerbyStatus.Nerwork == DerbyBase.status) { networkRadio.setSelected(true); derbyStatus.setText(MessageFormat.format(message("DerbyServerListening"), DerbyBase.port + "")); } else if (DerbyStatus.Embedded == DerbyBase.status) { embeddedRadio.setSelected(true); derbyStatus.setText(message("DerbyEmbeddedMode")); } else { networkRadio.setSelected(false); embeddedRadio.setSelected(false);
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlData2DSource.java
released/MyBox/src/main/java/mara/mybox/controller/ControlData2DSource.java
package mara.mybox.controller; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2021-10-18 * @License Apache License Version 2.0 */ public class ControlData2DSource extends BaseData2DRowsColumnsController { @Override public void updateStatus() { try { super.updateStatus(); if (fileMenuButton != null) { fileMenuButton.setVisible(data2D != null && data2D.isDataFile() && data2D.getFile() != null); } } catch (Exception e) { MyBoxLog.error(e); } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/MyBoxLogViewerController.java
released/MyBox/src/main/java/mara/mybox/controller/MyBoxLogViewerController.java
package mara.mybox.controller; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.CheckBox; import javafx.stage.Window; import mara.mybox.db.table.TableMyBoxLog; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.NodeTools; import mara.mybox.fxml.WindowTools; import mara.mybox.value.AppVariables; import mara.mybox.value.Fxmls; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2020-11-27 * @License Apache License Version 2.0 */ public class MyBoxLogViewerController extends HtmlTableController { protected TableMyBoxLog logTable; @FXML protected CheckBox popCheck; public MyBoxLogViewerController() { baseTitle = Languages.message("MyBoxLogsViewer"); } @Override public void initValues() { try { super.initValues(); logTable = new TableMyBoxLog(); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void initControls() { try { super.initControls(); AppVariables.popErrorLogs = UserConfig.getBoolean("PopErrorLogs", true); popCheck.setSelected(AppVariables.popErrorLogs); popCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { AppVariables.popErrorLogs = popCheck.isSelected(); UserConfig.setBoolean("PopErrorLogs", popCheck.isSelected()); } }); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean afterSceneLoaded() { try { if (!super.afterSceneLoaded()) { return false; } myStage.setWidth(600); myStage.setHeight(500); myStage.setY(5); myStage.setX(NodeTools.getScreen().getWidth() - 610); return true; } catch (Exception e) { System.out.println(e.toString()); return false; } } // Avoid interface blocked when logs flooding @Override public void toFront() { } @FXML public void manageAction(ActionEvent event) { MyBoxLogController.oneOpen(); setIconified(true); } @FXML public void messageAction(ActionEvent event) { MessageAuthorController controller = (MessageAuthorController) WindowTools.openStage(Fxmls.MessageAuthorFxml); controller.loadMessage("MyBox Logs", html); } @FXML public void clearAction(ActionEvent event) { body = null; displayHtml(null); } public void addLog(MyBoxLog myboxLog) { body = (body != null ? body : "") + "</br><hr></br>\n" + logTable.htmlTable(myboxLog).div(); loadBody(body); } public void setLogs(List<MyBoxLog> logs) { body = ""; for (MyBoxLog log : logs) { body += "</br><hr></br>\n" + logTable.htmlTable(log).div(); } loadBody(body); } public static MyBoxLogViewerController oneOpen() { MyBoxLogViewerController controller = null; List<Window> windows = new ArrayList<>(); windows.addAll(Window.getWindows()); for (Window window : windows) { Object object = window.getUserData(); if (object != null && object instanceof MyBoxLogViewerController) { try { controller = (MyBoxLogViewerController) object; break; } catch (Exception e) { } } } if (controller == null) { controller = (MyBoxLogViewerController) WindowTools.openStage(Fxmls.MyBoxLogViewerFxml); } return controller; } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/BaseDataFileConvertController.java
released/MyBox/src/main/java/mara/mybox/controller/BaseDataFileConvertController.java
package mara.mybox.controller; import java.io.File; import java.util.List; import javafx.fxml.FXML; import javafx.scene.layout.VBox; import mara.mybox.data2d.operate.Data2DExport; import mara.mybox.dev.MyBoxLog; import mara.mybox.tools.FileNameTools; import mara.mybox.value.Languages; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2020-12-05 * @License Apache License Version 2.0 */ public abstract class BaseDataFileConvertController extends BaseBatchFileController { protected Data2DExport export; protected boolean skip; @FXML protected VBox convertVBox; @FXML protected ControlDataExport convertController; public BaseDataFileConvertController() { baseTitle = Languages.message("dataConvert"); } @Override public void initOptionsSection() { try { super.initOptionsSection(); convertController.setParameters(this); } catch (Exception e) { MyBoxLog.error(e); } } @Override public boolean makeMoreParameters() { export = convertController.pickParameters(null); if (export == null) { return false; } export.setController(this); skip = targetPathController.isSkip(); return super.makeMoreParameters(); } public String filePrefix(File srcFile) { if (srcFile == null) { return null; } return FileNameTools.prefix(srcFile.getName()); } @Override public void disableControls(boolean disable) { super.disableControls(disable); convertVBox.setDisable(disable); } @Override public void handleTargetFiles() { List<File> files = export.getPrintedFiles(); targetFilesCount = files != null ? files.size() : 0; if (!isPreview && openCheck != null && !openCheck.isSelected()) { return; } if (targetFilesCount > 0) { File path = files.get(0).getParentFile(); browseURI(path.toURI()); recordFileOpened(path); } else { popInformation(message("NoFileGenerated")); } } @FXML @Override public void openTarget() { } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ControlDataHtml.java
released/MyBox/src/main/java/mara/mybox/controller/ControlDataHtml.java
package mara.mybox.controller; import javafx.fxml.FXML; import mara.mybox.db.data.DataNode; import mara.mybox.dev.MyBoxLog; /** * @Author Mara * @CreateDate 2024-8-8 * @License Apache License Version 2.0 */ public class ControlDataHtml extends BaseDataValuesController { @FXML protected ControlHtmlMaker htmlController; @Override public void initEditor() { try { htmlController.setParameters(this); } catch (Exception e) { MyBoxLog.error(e); } } @Override protected void editValues() { try { isSettingValues = true; if (nodeEditor.currentNode != null) { htmlController.loadContents(nodeEditor.currentNode.getStringValue("html")); } else { htmlController.loadContents(null); } htmlController.updateStatus(false); isSettingValues = false; valueChanged(false); } catch (Exception e) { MyBoxLog.error(e); } } @Override protected DataNode pickValues(DataNode node) { try { node.setValue("html", htmlController.currentHtml()); return node; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ChromaticityDiagramController.java
released/MyBox/src/main/java/mara/mybox/controller/ChromaticityDiagramController.java
package mara.mybox.controller; import java.awt.color.ColorSpace; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import javafx.beans.binding.Bindings; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.embed.swing.SwingFXUtils; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.RadioButton; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.paint.Color; import mara.mybox.color.CIEColorSpace; import mara.mybox.color.CIEData; import mara.mybox.color.CIEDataTools; import mara.mybox.color.ChromaticityDiagram; import mara.mybox.color.ChromaticityDiagram.DataType; import mara.mybox.color.ColorValue; import mara.mybox.color.SRGB; import mara.mybox.data.StringTable; import mara.mybox.db.data.VisitHistory; import mara.mybox.db.data.VisitHistoryTools; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.FxSingletonTask; import mara.mybox.fxml.HelpTools; import mara.mybox.fxml.menu.MenuTools; import mara.mybox.fxml.RecentVisitMenu; import mara.mybox.fxml.image.FxImageTools; import mara.mybox.fxml.image.ImageViewTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.image.data.ImageColorSpace; import mara.mybox.image.file.ImageFileWriters; import mara.mybox.tools.DoubleTools; import mara.mybox.tools.FileNameTools; import mara.mybox.tools.FloatTools; import mara.mybox.tools.TextFileTools; import mara.mybox.value.AppVariables; import mara.mybox.value.FileFilters; import mara.mybox.value.Languages; import mara.mybox.value.UserConfig; /** * @Author Mara * @CreateDate 2019-5-20 * @License Apache License Version 2.0 */ public class ChromaticityDiagramController extends BaseImageController { protected boolean isLine, inputInit = true; protected int dotSize, fontSize; protected java.awt.Color bgColor, calculateColor; protected final ObservableList<ColorValue> calculatedValues = FXCollections.observableArrayList(); protected ObservableList<CIEData> degree2nm1Data, degree10nm1Data, degree2nm5Data, degree10nm5Data; protected double X, Y = 1, Z, x = 0.4, y = 0.5; @FXML protected TabPane displayPane; @FXML protected Tab diaTab, cie21Tab, cie25Tab, cie101Tab, cie105Tab; @FXML protected ComboBox<String> fontSelector; @FXML protected CheckBox cdProPhotoCheck, cdColorMatchCheck, cdNTSCCheck, cdPALCheck, cdAppleCheck, cdAdobeCheck, cdSRGBCheck, cdECICheck, cdCIECheck, cdSMPTECCheck, degree2Check, degree10Check, waveCheck, whitePointsCheck, cdGridCheck, calculateCheck, inputCheck; @FXML protected TextArea sourceInputArea, sourceDataArea; @FXML protected HtmlTableController calculateViewController, d2n1Controller, d2n5Controller, d10n1Controller, d10n5Controller; @FXML protected TextField XInput, YInput, ZInput, xInput, yInput; @FXML protected Button okSizeButton, calculateXYZButton, calculateXYButton, displayDataButton; @FXML protected ControlColorSet colorSetController; @FXML protected ToggleGroup bgGroup, dotGroup; @FXML protected RadioButton bgTransparentRadio, bgWhiteRadio, bgBlackRadio, dotLine4pxRadio, dotDot6pxRadio, dotDot10pxRadio, dotDot4pxRadio, dotDot12pxRadio, dotLine1pxRadio, dotLine2pxRadio, dotLine6pxRadio, dotLine10pxRadio; public ChromaticityDiagramController() { baseTitle = Languages.message("DrawChromaticityDiagram"); TipsLabelKey = "ChromaticityDiagramTips"; } @Override public void setFileType() { setFileType(VisitHistory.FileType.Text); } @Override public void initControls() { try { super.initControls(); initDisplay(); initDataBox(); initCIEData(); initDiagram(); } catch (Exception e) { MyBoxLog.error(e); } } @Override public void setControlsStyle() { try { super.setControlsStyle(); NodeStyleTools.setTooltip(YInput, new Tooltip(Languages.message("1-based"))); } catch (Exception e) { MyBoxLog.debug(e); } } private void initDisplay() { try { bgGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) { checkBackground(); } }); dotGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) { checkDotType(); } }); List<String> fontList = Arrays.asList("20", "24", "28", "30", "18", "16", "15", "14", "12", "10"); fontSelector.getItems().addAll(fontList); fontSelector.setVisibleRowCount(fontList.size()); fontSelector.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { checkFontSize(); } }); calculateCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { if (!isSettingValues) { displayChromaticityDiagram(); } } }); inputCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); waveCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdGridCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); whitePointsCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); degree2Check.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); degree10Check.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdProPhotoCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdColorMatchCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdNTSCCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdPALCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdAppleCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdAdobeCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdSRGBCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdECICheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdCIECheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); cdSMPTECCheck.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) { displayChromaticityDiagram(); } }); isSettingValues = true; bgColor = null; isLine = true; dotSize = 4; bgTransparentRadio.setSelected(true); dotLine4pxRadio.setSelected(true); fontSelector.getSelectionModel().select(0); isSettingValues = false; } catch (Exception e) { MyBoxLog.error(e); } } private void initDiagram() { try { colorSetController.setNotify.addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> v, Boolean ov, Boolean nv) { calculateColor(); } }); imageView.fitWidthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) { if (Math.abs(new_val.intValue() - old_val.intValue()) > 20) { refinePane(); } } }); imageView.fitHeightProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) { if (Math.abs(new_val.intValue() - old_val.intValue()) > 20) { refinePane(); } } }); scrollPane.widthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> ov, Number old_val, Number new_val) { if (Math.abs(new_val.intValue() - old_val.intValue()) > 20) { refinePane(); } } }); } catch (Exception e) { MyBoxLog.error(e); } } private void initDataBox() { try { XInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { X = Double.parseDouble(newValue); XInput.setStyle(null); } catch (Exception e) { XInput.setStyle(UserConfig.badStyle()); } } }); YInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { Y = Double.parseDouble(newValue); if (Y == 0) { YInput.setStyle(UserConfig.badStyle()); } else { YInput.setStyle(null); } } catch (Exception e) { YInput.setStyle(UserConfig.badStyle()); } } }); ZInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { Z = Double.parseDouble(newValue); ZInput.setStyle(null); } catch (Exception e) { ZInput.setStyle(UserConfig.badStyle()); } } }); xInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { x = Double.parseDouble(newValue); double z = 1 - x - y; if (x > 1 || x < 0 || z < 0 || z > 1) { xInput.setStyle(UserConfig.badStyle()); } else { xInput.setStyle(null); } } catch (Exception e) { xInput.setStyle(UserConfig.badStyle()); } } }); yInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { try { y = Double.parseDouble(newValue); double z = 1 - x - y; if (y > 1 || y <= 0 || z < 0 || z > 1) { yInput.setStyle(UserConfig.badStyle()); } else { yInput.setStyle(null); } } catch (Exception e) { yInput.setStyle(UserConfig.badStyle()); } } }); calculateXYZButton.disableProperty().bind(Bindings.isEmpty(XInput.textProperty()) .or(XInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(YInput.textProperty())) .or(YInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(ZInput.textProperty())) .or(ZInput.styleProperty().isEqualTo(UserConfig.badStyle())) ); calculateXYButton.disableProperty().bind(Bindings.isEmpty(xInput.textProperty()) .or(xInput.styleProperty().isEqualTo(UserConfig.badStyle())) .or(Bindings.isEmpty(yInput.textProperty())) .or(yInput.styleProperty().isEqualTo(UserConfig.badStyle())) ); displayDataButton.disableProperty().bind(Bindings.isEmpty(sourceDataArea.textProperty()) ); sourceInputArea.setStyle(" -fx-text-fill: gray;"); sourceInputArea.setText(Languages.message("ChromaticityDiagramTips")); sourceInputArea.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed( ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (inputInit) { sourceInputArea.clear(); sourceInputArea.setStyle(null); inputInit = false; } } }); sourceInputArea.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (isSettingValues) { return; } checkInputs(); } }); } catch (Exception e) { MyBoxLog.error(e); } } private void checkInputs() { String data = CIEDataTools.cieString(sourceInputArea.getText()); if (data != null) { sourceDataArea.setText(data); } else { popError(Languages.message("NoData")); sourceDataArea.clear(); } } private void checkDotType() { isLine = false; if (dotDot6pxRadio.isSelected()) { dotSize = 6; } else if (dotDot10pxRadio.isSelected()) { dotSize = 10; } else if (dotDot4pxRadio.isSelected()) { dotSize = 4; } else if (dotDot12pxRadio.isSelected()) { dotSize = 12; } else if (dotLine4pxRadio.isSelected()) { isLine = true; dotSize = 4; } else if (dotLine1pxRadio.isSelected()) { isLine = true; dotSize = 1; } else if (dotLine2pxRadio.isSelected()) { isLine = true; dotSize = 2; } else if (dotLine6pxRadio.isSelected()) { isLine = true; dotSize = 6; } else if (dotLine10pxRadio.isSelected()) { isLine = true; dotSize = 10; } else { dotSize = 6; } if (!isSettingValues) { displayChromaticityDiagram(); } } private void checkBackground() { if (bgTransparentRadio.isSelected()) { bgColor = null; } else if (bgWhiteRadio.isSelected()) { bgColor = java.awt.Color.WHITE; } else if (bgBlackRadio.isSelected()) { bgColor = java.awt.Color.BLACK; } else { bgColor = null; } if (!isSettingValues) { displayChromaticityDiagram(); } } private void checkFontSize() { try { int v = Integer.parseInt(fontSelector.getValue()); if (v > 0) { fontSize = v; fontSelector.getEditor().setStyle(null); if (!isSettingValues) { displayChromaticityDiagram(); } } else { fontSelector.getEditor().setStyle(UserConfig.badStyle()); } } catch (Exception e) { fontSelector.getEditor().setStyle(UserConfig.badStyle()); } } private void initCIEData() { if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { private StringTable degree2nm1Table, degree10nm1Table, degree2nm5Table, degree10nm5Table; @Override protected boolean handle() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); degree2nm1Data = FXCollections.observableArrayList(); degree2nm1Data.addAll(CIEDataTools.cie1931Observer2Degree1nmData(cs)); degree2nm1Table = CIEDataTools.cieTable(degree2nm1Data, cs, Languages.message("CIE1931Observer2DegreeAndSRGB")); degree2nm5Data = FXCollections.observableArrayList(); degree2nm5Data.addAll(CIEDataTools.cie1931Observer2Degree5nmData(cs)); degree2nm5Table = CIEDataTools.cieTable(degree2nm5Data, cs, Languages.message("CIE1931Observer2DegreeAndSRGB")); degree10nm1Data = FXCollections.observableArrayList(); degree10nm1Data.addAll(CIEDataTools.cie1964Observer10Degree1nmData(cs)); degree10nm1Table = CIEDataTools.cieTable(degree10nm1Data, cs, Languages.message("CIE1964Observer10DegreeAndSRGB")); degree10nm5Data = FXCollections.observableArrayList(); degree10nm5Data.addAll(CIEDataTools.cie1964Observer10Degree5nmData(cs)); degree10nm5Table = CIEDataTools.cieTable(degree10nm5Data, cs, Languages.message("CIE1964Observer10DegreeAndSRGB")); return true; } @Override protected void whenSucceeded() { d2n1Controller.loadTable(degree2nm1Table); d2n5Controller.loadTable(degree2nm5Table); d10n1Controller.loadTable(degree10nm1Table); d10n5Controller.loadTable(degree10nm5Table); afterInitCIEData(); } }; start(task); } private void afterInitCIEData() { colorSetController.init(this, baseName + "Color"); } @Override public void sourceFileChanged(final File file) { if (file == null) { return; } if (task != null && !task.isQuit()) { return; } task = new FxSingletonTask<Void>(this) { private String texts; @Override protected boolean handle() { texts = TextFileTools.readTexts(this, file); return texts != null; } @Override protected void whenSucceeded() { sourceInputArea.setStyle(null); inputInit = false; // bottomLabel.setText(file.getAbsolutePath() + "\t" + AppVariables.getMessage("ChromaticityDiagramComments")); isSettingValues = true; sourceInputArea.setText(texts); sourceInputArea.home(); isSettingValues = false; checkInputs(); } @Override protected void whenFailed() { popError(Languages.message("NoData")); sourceDataArea.clear(); } }; start(task); } @FXML public void displayDataAction() { if (sourceDataArea.getText().isEmpty()) { return; } isSettingValues = true; inputCheck.setSelected(true); isSettingValues = false; displayChromaticityDiagram(); } public void showDiagramPathMenu(Event event) { if (AppVariables.fileRecentNumber <= 0) { return; } new RecentVisitMenu(this, event, true) { @Override public List<VisitHistory> recentPaths() { return VisitHistoryTools.getRecentPathWrite(VisitHistory.FileType.Image); } @Override public void handleSelect() { saveAction(); } @Override public void handlePath(String fname) { handleTargetPath(fname); } }.pop(); } @FXML public void pickDiagramPath(Event event) { if (MenuTools.isPopMenu("RecentVisit") || AppVariables.fileRecentNumber <= 0) { saveAction(); } else { showDiagramPathMenu(event); } } @FXML public void popDiagramPath(Event event) { if (MenuTools.isPopMenu("RecentVisit")) { showDiagramPathMenu(event); } } @FXML public void noElements() { isSettingValues = true; cdProPhotoCheck.setSelected(false); cdColorMatchCheck.setSelected(false); cdNTSCCheck.setSelected(false); cdPALCheck.setSelected(false); cdAppleCheck.setSelected(false); cdAdobeCheck.setSelected(false); cdSRGBCheck.setSelected(false); cdECICheck.setSelected(false); cdCIECheck.setSelected(false); cdSMPTECCheck.setSelected(false); degree2Check.setSelected(false); degree10Check.setSelected(false); waveCheck.setSelected(false); inputCheck.setSelected(false); calculateCheck.setSelected(false); whitePointsCheck.setSelected(false); isSettingValues = false; displayChromaticityDiagram(); } @FXML public void allElements() { isSettingValues = true; cdProPhotoCheck.setSelected(true); cdColorMatchCheck.setSelected(true); cdNTSCCheck.setSelected(true); cdPALCheck.setSelected(true); cdAppleCheck.setSelected(true); cdAdobeCheck.setSelected(true); cdSRGBCheck.setSelected(true); cdECICheck.setSelected(true); cdCIECheck.setSelected(true); cdSMPTECCheck.setSelected(true); degree2Check.setSelected(true); degree10Check.setSelected(true); waveCheck.setSelected(true); inputCheck.setSelected(true); calculateCheck.setSelected(true); whitePointsCheck.setSelected(true); isSettingValues = false; displayChromaticityDiagram(); } @Override public double scale(double d) { return DoubleTools.scale(d, 8); } protected void calculateColor() { CIEData d = new CIEData((Color) colorSetController.rect.getFill()); isSettingValues = true; XInput.setText(scale(d.getX()) + ""); YInput.setText(scale(d.getY()) + ""); ZInput.setText(scale(d.getZ()) + ""); calculateXYZAction(); isSettingValues = false; if (calculateCheck.isSelected()) { displayChromaticityDiagram(); } } @FXML public void calculateXYZAction() { CIEData d = new CIEData(-1, X, Y, Z); xInput.setText(scale(d.getNormalizedX()) + ""); yInput.setText(scale(d.getNormalizedY()) + ""); displayCalculatedValued(); } @FXML public void calculateXYAction() { CIEData d = new CIEData(x, y); XInput.setText(scale(d.getX()) + ""); YInput.setText(scale(d.getY()) + ""); ZInput.setText(scale(d.getZ()) + ""); displayCalculatedValued(); } private void displayCalculatedValued() { if (x >= 0 && x <= 1 && y > 0 && y <= 1 && (x + y) <= 1) { double[] srgb = CIEColorSpace.XYZd50toSRGBd65(X, Y, Z); if (!isSettingValues) { isSettingValues = true; Color pColor = new Color((float) srgb[0], (float) srgb[1], (float) srgb[2], 1d); colorSetController.rect.setFill(pColor); isSettingValues = false; } Color pColor = (Color) colorSetController.rect.getFill(); calculateColor = new java.awt.Color((float) pColor.getRed(), (float) pColor.getGreen(), (float) pColor.getBlue()); List<ColorValue> values = new ArrayList<>(); double[] XYZ = {X, Y, Z}; values.add(new ColorValue("XYZ", "D50", XYZ)); double[] xyz = {x, y, 1 - x - y}; values.add(new ColorValue("xyz", "D50", xyz)); double[] cieLab = CIEColorSpace.XYZd50toCIELab(X, Y, Z); values.add(new ColorValue("CIE-L*ab", "D50", cieLab)); double[] LCHab = CIEColorSpace.LabtoLCHab(cieLab); values.add(new ColorValue("LCH(ab)", "D50", LCHab)); double[] cieLuv = CIEColorSpace.XYZd50toCIELuv(X, Y, Z); values.add(new ColorValue("CIE-L*uv", "D50", cieLuv)); double[] LCHuv = CIEColorSpace.LuvtoLCHuv(cieLuv); values.add(new ColorValue("LCH(uv)", "D50", LCHuv)); double[] hsb = {pColor.getHue(), pColor.getSaturation(), pColor.getBrightness()}; values.add(new ColorValue("HSB", "D65", hsb)); values.add(new ColorValue("sRGB", "D65 sRGB_Gamma", srgb, 255)); double[] sRGBLinear = CIEColorSpace.XYZd50toSRGBd65Linear(X, Y, Z); values.add(new ColorValue("sRGB", "D65 Linear", sRGBLinear, 255)); double[] adobeRGB = CIEColorSpace.XYZd50toAdobeRGBd65(X, Y, Z); values.add(new ColorValue("Adobe RGB", "D65 Gamma 2.2", adobeRGB, 255)); double[] adobeRGBLinear = CIEColorSpace.XYZd50toAdobeRGBd65Linear(X, Y, Z); values.add(new ColorValue("Adobe RGB", "D65 Linear", adobeRGBLinear, 255)); double[] appleRGB = CIEColorSpace.XYZd50toAppleRGBd65(X, Y, Z); values.add(new ColorValue("Apple RGB", "D65 Gamma 1.8", appleRGB, 255)); double[] appleRGBLinear = CIEColorSpace.XYZd50toAppleRGBd65Linear(X, Y, Z); values.add(new ColorValue("Apple RGB", "D65 Linear", appleRGBLinear, 255)); float[] eciRGB = SRGB.srgb2profile(ImageColorSpace.eciRGBProfile(), pColor); values.add(new ColorValue("ECI RGB", "D50", FloatTools.toDouble(eciRGB), 255)); double[] cmyk = SRGB.rgb2cmyk(pColor); values.add(new ColorValue("Calculated CMYK", "D65 sRGB_Gamma", cmyk, 100)); float[] cmyk2 = SRGB.srgb2profile(ImageColorSpace.eciCmykProfile(), pColor); values.add(new ColorValue("ECI CMYK", "D65 sRGB_Gamma", FloatTools.toDouble(cmyk2), 100)); cmyk2 = SRGB.srgb2profile(ImageColorSpace.adobeCmykProfile(), pColor); values.add(new ColorValue("Adobe CMYK Uncoated FOGRA29", "D65 sRGB_Gamma", FloatTools.toDouble(cmyk2), 100)); calculatedValues.clear(); calculatedValues.addAll(values); List<String> names = new ArrayList<>(); names.addAll(Arrays.asList(Languages.message("ColorSpace"), Languages.message("Conditions"), Languages.message("Values"))); StringTable table = new StringTable(names, null); for (ColorValue value : calculatedValues) { List<String> row = new ArrayList<>(); row.addAll(Arrays.asList(value.getColorSpace(), value.getConditions(), value.getValues())); table.add(row); } calculateViewController.loadTable(table); if (calculateCheck.isSelected()) {
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
true
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/XYZController.java
released/MyBox/src/main/java/mara/mybox/controller/XYZController.java
package mara.mybox.controller; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import mara.mybox.color.CIEData; import mara.mybox.color.CIEDataTools; import mara.mybox.fxml.style.NodeStyleTools; import mara.mybox.value.UserConfig; import mara.mybox.tools.DoubleTools; import static mara.mybox.value.Languages.message; import mara.mybox.value.Languages; /** * @Author Mara * @CreateDate 2019-6-2 * @License Apache License Version 2.0 */ public class XYZController extends BaseController { protected double x, y, z; protected double[] relative; protected ValueType valueType; protected int scale = 8; public enum ValueType { Relative, Normalized, Tristimulus } @FXML protected TextField xInput, yInput, zInput; @FXML protected ToggleGroup valueGroup; @FXML protected Label xLabel, yLabel, zLabel, commentsLabel; public XYZController() { } @Override public void initControls() { try { super.initControls(); valueGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public void changed(ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) { checkValueType(); } }); xInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { checkInputs(); } }); yInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { checkInputs(); } }); zInput.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { checkInputs(); } }); checkValueType(); } catch (Exception e) { } } public void checkValueType() { isSettingValues = true; xInput.setText(""); yInput.setText(""); zInput.setText(""); yInput.setDisable(false); zInput.setDisable(false); if (commentsLabel != null) { commentsLabel.setText(""); commentsLabel.setStyle(null); } RadioButton selected = (RadioButton) valueGroup.getSelectedToggle(); if (Languages.message("NormalizedValuesCC").equals(selected.getText())) { valueType = ValueType.Normalized; xLabel.setText("x"); yLabel.setText("y"); zLabel.setText("z"); zInput.setDisable(true); } else if (Languages.message("Tristimulus").equals(selected.getText())) { valueType = ValueType.Tristimulus; xLabel.setText("X'"); yLabel.setText("Y'"); zLabel.setText("Z'"); } else { valueType = ValueType.Relative; xLabel.setText("X"); yLabel.setText("Y"); yInput.setText("1.0"); yInput.setDisable(true); zLabel.setText("Z"); } isSettingValues = false; checkValues(); } public void checkValues() { checkInputs(); } public void checkInputs() { if (isSettingValues) { return; } if (commentsLabel != null) { commentsLabel.setText(""); commentsLabel.setStyle(null); } try { double v = Double.parseDouble(xInput.getText()); if (v < 0) { xInput.setStyle(UserConfig.badStyle()); return; } else { if (valueType == ValueType.Normalized) { if (v > 1.0) { xInput.setStyle(UserConfig.badStyle()); if (commentsLabel != null) { commentsLabel.setText(Languages.message("NormalizeError")); commentsLabel.setStyle(UserConfig.badStyle()); } return; } } x = v; xInput.setStyle(null); } } catch (Exception e) { xInput.setStyle(UserConfig.badStyle()); return; } try { double v = Double.parseDouble(yInput.getText()); if (v < 0) { yInput.setStyle(UserConfig.badStyle()); return; } else { if (valueType == ValueType.Normalized) { if (v > 1.0) { yInput.setStyle(UserConfig.badStyle()); if (commentsLabel != null) { commentsLabel.setText(Languages.message("NormalizeError")); commentsLabel.setStyle(UserConfig.badStyle()); } return; } } y = v; yInput.setStyle(null); } } catch (Exception e) { yInput.setStyle(UserConfig.badStyle()); return; } if (valueType == ValueType.Normalized) { isSettingValues = true; z = DoubleTools.scale(1 - x - y, scale); zInput.setText(z + ""); isSettingValues = false; } else { try { double v = Double.parseDouble(zInput.getText()); z = v; zInput.setStyle(null); } catch (Exception e) { zInput.setStyle(UserConfig.badStyle()); return; } } relative = CIEDataTools.relative(x, y, z); } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false
Mararsh/MyBox
https://github.com/Mararsh/MyBox/blob/107ddc379fd2f4caad37e85c29367d21089b568c/released/MyBox/src/main/java/mara/mybox/controller/ColorPaletteSelectorController.java
released/MyBox/src/main/java/mara/mybox/controller/ColorPaletteSelectorController.java
package mara.mybox.controller; import javafx.fxml.FXML; import javafx.scene.input.MouseEvent; import mara.mybox.db.data.ColorPaletteName; import mara.mybox.db.table.TableColor; import mara.mybox.db.table.TableColorPalette; import mara.mybox.dev.MyBoxLog; import mara.mybox.fxml.WindowTools; import mara.mybox.value.Fxmls; import static mara.mybox.value.Languages.message; /** * @Author Mara * @CreateDate 2023-3-10 * @License Apache License Version 2.0 */ public class ColorPaletteSelectorController extends BaseChildController { protected TableColor tableColor; protected TableColorPalette tableColorPalette; protected ColorPalettePopupController popupController; @FXML protected ControlColorPaletteSelector palettesController; public ColorPaletteSelectorController() { baseTitle = message("SelectColorPalette"); } public void setParameter(ColorPalettePopupController popupController) { try { super.initControls(); this.popupController = popupController; palettesController.setParameter(null, false); okButton.disableProperty().bind(palettesController.palettesList.getSelectionModel().selectedItemProperty().isNull()); palettesController.loadPalettes(); palettesController.palettesList.setOnMouseClicked((MouseEvent event) -> { if (event.getClickCount() > 1) { okAction(); } }); } catch (Exception e) { MyBoxLog.error(e); } } @FXML @Override public void okAction() { ColorPaletteName palette = palettesController.palettesList.getSelectionModel().getSelectedItem(); if (palette == null) { popError(message("SelectPaletteCopyColors")); return; } close(); popupController.loadPalette(palette.getName()); } @FXML @Override public void cancelAction() { closeStage(); } /* static */ public static ColorPaletteSelectorController open(ColorPalettePopupController popupController) { try { ColorPaletteSelectorController controller = (ColorPaletteSelectorController) WindowTools.childStage( popupController, Fxmls.ColorPaletteSelectorFxml); controller.setParameter(popupController); return controller; } catch (Exception e) { MyBoxLog.error(e); return null; } } }
java
Apache-2.0
107ddc379fd2f4caad37e85c29367d21089b568c
2026-01-05T02:30:12.428303Z
false